Blocks
Page-builder blocks with @cms/blocks, a block playground in the admin, and the canvas route that renders them on your website.
@cms/blocks is for page builders made of blocks. It adds:
blocks(), aunion()whose “Add” opens the block picker: a searchable, grouped list of blocks and their presets beside a live preview (see the Blocks pattern)blocksPlugin(), a block playground in the admin: every block type, started from a preset or empty, edited and rendered live by your website, with nothing saved@cms/blocks/canvas, the hook for the block canvas: the route on your website that renders blocks the admin sends it
pnpm add @cms/blocks
Block picker
“Add item”, and the + between two rows, open the picker. Its title says where the block goes, with
the field’s label and the row before it as the array shows that row: “Blocks, after FAQ” (or
“before …” at the top, and just “Blocks” in an empty list).
- The list (left) shows every block, under its group. A block with presets stands for
its first preset, whose label shows beside the block’s name; expanding it lists its other presets
beneath it. Every block is collapsed when the picker opens; any number can be expanded at once,
and each block’s caret expands or collapses only its own presets. Hovering or searching never
expands a block, so the list stays put under the pointer. A block without
presets is its empty default. There’s no “Empty” item in the picker: to test a block’s
empty state, use the playground. Search finds a block by its title or by
its
keywordsin any locale; expanded blocks stay expanded across a search. - The preview (right) shows the highlighted item. The picker opens on the first block, so the
preview starts on its first preset rather than an empty block. With a
canvasit’s rendered live by your website at desktop width (1280px), scaled down to fit the pane, with relations loaded as live preview loads them; without one it’s the block’s staticthumbnail(or its icon), with the preset’s first text below its name. - The keyboard. Typing searches; the up and down arrows move through the blocks and the expanded blocks’ presets without expanding or collapsing anything; the right arrow expands the highlighted block and the left arrow collapses it (from a preset, back to its block); Enter inserts. A click on a row inserts too. Choosing a block with presets inserts its first preset.
- The locale is the document’s: presets show with that locale’s
localesoverrides, the canvas renders in it, and the block is inserted in it. Only a document without a locale (an entity that isn’t translatable) shows a locale switch, starting on the default locale; it changes only the preview, and the block goes in without locale overrides.
A block is inserted the moment it’s chosen, at the position the picker was opened for, and its row opens, so the editor carries on in the document with the page’s own live preview.
Groups
A variant’s group lists it under a heading. It’s admin text, so it’s a plain label shown as is
in every locale (the admin is English-only); only presets and keywords take per-locale values.
Groups show in the order they’re first used. With no groups, the list is flat.
blocks("section", {
of: [hero, productGrid, faq],
variants: {
hero: { group: "Editorial" },
productGrid: { group: "Product" },
faq: { group: "Editorial" },
},
});
What each block needs
The picker draws every block from its definition and its variants entry, and falls back to a bare
tile for anything missing. Give each block in a blocks() field:
titleanddescriptionon theobject(). The title names it in the list and the preview (without one, the raw type name shows); the description shows under it when no preset is highlighted.- A
variantsentry with itsgroup, anicon(otherwise a generic puzzle icon), athumbnail(the preview when the field has nocanvas) andpresets.
const hero = object("hero", {
title: "Hero",
description: "Full-width heading over an image",
fields: [/* … */],
});
blocks("section", {
of: [hero, faq],
variants: {
hero: {
group: "Editorial",
icon: ImageIcon,
thumbnail: "/blocks/hero.png",
presets: [{ label: "Dark", value: { heading: "Made by hand", tone: "dark" } }],
},
// …
},
});
Presets are what a canvas renders: a block without them previews as an empty block, which is
usually a blank frame. Leave them out only when every field is a choice the editor makes after
placing the block, such as a product to show or a form to embed. Then there’s no content to
preview, and the block goes in empty either way. Without a canvas, the thumbnail and
description carry the picker. With one, the picker always renders the canvas, never the
thumbnail, so give the block’s website component an empty state that still reads as the block
(a placeholder card, say).
Block playground
Create the canvas once, with blockCanvas(), and pass it to the plugin and to every blocks()
field:
// cms.config.tsx
import { env } from "@cms/client";
import { config } from "@cms/config";
import { blockCanvas, blocks, blocksPlugin } from "@cms/blocks";
const canvasUrl = new URL("/cms-canvas", env("CMS_PUBLIC_SITE_URL") ?? "http://localhost:3001");
// The canvas reads drafts with the preview key, e.g. to unwrap synced blocks.
canvasUrl.searchParams.set("token", env("CMS_PUBLIC_PREVIEW_API_KEY") ?? "");
export const canvas = blockCanvas({ url: canvasUrl.toString() });
const section = blocks("section", { of: [hero, faq], canvas, variants: { /* … */ } });
export default config({
// …
plugins: [blocksPlugin({ canvas, roles: ["designer"] })],
});
| Option | Description |
|---|---|
canvas |
The canvas the playground renders with, from blockCanvas({ url }). |
roles |
Roles (beyond admins, who always can) that may open the playground. Default: admins only. |
name |
The instance name, if blocks is taken. |
The playground is a page in the sidebar. It lists every block type of every blocks() field across
all entities (plugin ones included), once per type however many fields allow it, with the fields
and entities that use it, under a search box. For the selected block:
- Edit starts it from its first preset, or another one or Empty picked from the “Start from” menu (a block without presets starts empty), and shows its fields beside the canvas. Pick real images, relations and Shopify products: they reach the canvas loaded, the way live preview loads them. Edits are kept in memory only and nothing is ever saved: Reset, or changing the block, preset or locale, starts over from that starting value and drops your edits.
- All presets stacks every preset of the block in one canvas, in their order, read-only.
- The locale switch shows presets with their
localesoverrides and tells the canvas which locale to render. - The width switch shows the canvas at mobile (390px), desktop or full width. Desktop, the default, renders the site at 1280px scaled down to fit the frame, like the picker’s preview, so a laptop still shows the desktop layout.
The block, preset and locale are in the URL (?block=hero&preset=1&locale=pt, with
preset=empty for the empty block), so a reload or a shared link opens the same thing. A link
without preset, or with one that’s gone, opens the first preset.
blocks() without a canvas previews each block with its static thumbnail in the picker; no
canvas route is needed to adopt the picker.
The canvas route
The canvas is a route on your website. It calls useBlockCanvas and renders what it hands over
with your own block renderer and layout:
// src/routes/cms-canvas.tsx (TanStack Start shown)
import { useBlockCanvas } from "@cms/blocks/canvas";
import { createFileRoute } from "@tanstack/react-router";
import { Blocks } from "~/components/blocks";
export const Route = createFileRoute("/cms-canvas")({
// Keep the canvas out of search results.
head: () => ({ meta: [{ name: "robots", content: "noindex, nofollow" }] }),
component: Canvas,
});
function Canvas() {
const canvas = useBlockCanvas<Block>({ adminOrigin: import.meta.env.VITE_CMS_URL });
if (!canvas) return null;
return <Blocks blocks={canvas.blocks} locale={canvas.locale} />;
}
useBlockCanvas({ adminOrigin }) returns { blocks, locale }, or undefined until the admin’s
first message. blocks is an array of block values ({ _type, ... }) with their relations already
loaded. The hook:
- ignores messages from any origin other than
adminOrigin(the admin’s own, e.g.https://cms.example.com), so another site that frames your route can’t make it show content - ignores any message but
{ type: "cms-block-canvas", blocks, locale }, so a canvas is never mistaken for a live preview of a document - tells the admin it’s listening when it starts, so the admin sends the blocks again if its first message came before your route rendered
The admin posts only to the canvas URL’s origin, never to "*".
The route is yours to finish:
-
noindex. Keep the route out of search engines, and out of your sitemap. -
Preview token. Put the preview API key in the canvas URL (
?token=), as above, and read with a client made from it, as the live preview loader does. -
Synced blocks. A synced block pointer arrives as a pointer. Unwrap it the way your page preview does, with the token’s client and
draft: true:const { data: blocks } = useQuery({ queryKey: ["cms-canvas", canvas?.blocks, canvas?.locale], queryFn: () => unwrapSyncedBlocks(previewCms, canvas?.blocks ?? [], { draft: true, locale: canvas?.locale }), enabled: !!canvas, }); -
Empty states. A block without presets is inserted empty, the playground’s Empty shows any block that way, and presets leave out images and relations, so render something deliberate for a missing image, product or link instead of a broken block. Presets are partial: any field can be missing, required ones included, so a component that assumes one is set (
block.items.map(...)) crashes. Guard those reads, or wrap each block in an error boundary that renders your empty state. -
Route context. Put the route where your blocks get what they read from the route. If blocks read the locale or region from URL segments (
/$region/$locale/...), nest the canvas under them (/$region/$locale/cms-canvas). Whencanvas.localediffers from the URL’s locale, navigate to that locale’s canvas URL. -
Framing. If your site sends
Content-Security-Policy: frame-ancestorsorX-Frame-Options, allow the admin’s origin on the canvas route.
Previous
Overview
Next
Cloudflare