A drag-and-drop newsletter editor for React, an email-safe renderer that runs anywhere JavaScript does, and blocks that fill themselves from your own records.
Live demo · Rendered email · Architecture · Email clients · Roadmap · Contributing
Status: 0.1. Both packages are on npm:
@subterra-technologies/blockletterand@subterra-technologies/blockletter-react. Until 1.0, a minor version may change the API; each package's changelog says how.
Most email builders hand your users a blank canvas. Blockletter hands them an issue that is already mostly written. Your app registers small data sources (upcoming events, new members, recent posts, sponsors, a community calendar), and the matching blocks fill themselves for the dates the issue covers. The person writing it adds a note, reorders a few blocks, checks the preview and sends it.
The rule it was built on: if I entered it once, I shouldn't have to enter it again.
A new issue fills itself from an organisation's data. Every item stays editable, and a picker chooses which events make the cut.
- Why Blockletter
- The demo
- A tour
- How it works
- Getting started
- Examples
- Translating the editor
- Documents from other languages and LLMs
- The blocks
- Accessibility
- Development
- Contributing
- Issues that assemble themselves. List blocks fill from your records through a small
DataSourceinterface. Refresh re-reads them, a picker chooses items, and every word stays editable. - Email-safe by construction. Table layout, inline styles, web-safe fonts, absolute links, escaped text, sanitised rich text, a hidden preheader, a layout that reflows on phones while Outlook keeps its fixed 600px, and a plain-text version of every email. What each client gets.
- A renderer that runs anywhere.
renderEmail()is a pure function with zero dependencies: the same document renders the same email in the browser, a Node worker, an edge function or a database function. - Honest warnings. Rendering also says what to fix before sending: a missing unsubscribe link, an image without alt text, an image that only exists in the browser, or an email long enough for mail apps to clip.
- An accessible editor. Built to WCAG 2.2 AA and audited automatically at 1440, 768, 390 and 320px. Every drag-and-drop gesture has a keyboard path, and changes are announced.
- Undo for every change. Adding, moving, deleting, editing or refreshing a block, and changing the issue's settings, can all be undone and redone from the top bar or with Ctrl+Z (⌘Z), typing a burst at a time. Deleting a block asks nothing first: its toast offers Undo.
- Formatted writing. Text blocks take bold, italics, links and bulleted or numbered lists, from
a toolbar or with Ctrl/⌘ + B, I and K. Pasted text keeps those and loses the rest, so what is
stored is always a few tags the sanitiser passes.
RichTextFieldgives your own blocks the same. - Markdown in every free-text field. Letters, callouts, articles, image + text, columns, pull
quotes, sponsor notes and list introductions read
**bold**,*italic*,~~strike~~,[links](https://example.org),#headings, lists,>quotes and---dividers, in the email, its plain-text part and on the canvas, so an AI assistant's answer pasted in arrives formatted. Each field has a toolbar that writes the marks for you.ctx.markdown(),MarkdownFieldandEmailMarkdowngive your own blocks the same. - Your backend, your workflow.
NewsletterEditoris a controlled React component. You store the documents, images and brand kits, and you decide who approves an issue and how it is sent. - Brand kits and templates. Logo, colours, fonts and contact details restyle every block, and
every colour pair is checked for contrast. Templates are saved layouts with tokens such as
{{monthYear}}. - In your language. Every word the editor shows or says can be translated, and the email's own words are yours to set too. How.
- Extensible. The 21 built-in blocks use the same
defineBlockAPI you use for your own.
The demo opens as the editor itself, filling the screen the way it would inside your app: the palette, the canvas and the inspector each scroll on their own, and on a phone it shows one pane at a time. Docs, one click away in its top bar, pairs each explanation and its code with the live piece it describes, all driven by the issue open in the editor. It opens on Field Notes, a newsletter built from Subterra Technologies' own website; a fictional makers' guild shows every data-bound block filling itself.
Each link below opens the live demo on a particular view. Running it locally, add the same query
or fragment to http://localhost:5173/.
| Try this | Link |
|---|---|
| Edit a newsletter | Field Notes, banner selected |
| Watch an issue assemble itself from data | New issue for a makers' guild |
| Choose which events a data-filled block shows | Event tiles and their picker |
| Restyle every block at once | Brand kit |
| Preview the email at desktop and phone widths | Preview |
| Use the editor in the dark | Dark theme |
| Read the email exactly as an inbox receives it | Rendered HTML |
| …and the plain-text version sent with it | Plain text |
| Read the docs beside the live pieces | Docs |
| See the renderer's output for the open issue | Rendering |
Add blocks from the palette or drag them onto the canvas. Each block has a toolbar to move, insert next to, hide, duplicate, refresh or delete it, and every one of those works from the keyboard.
A block that names a data source is auto-filled. The inspector lists what the source offers for the issue's dates; checking and unchecking items updates the block, and items written by hand sit alongside the sourced ones.
![]() |
![]() |
The preview renders the real email in a sandboxed frame, at 600px for desktop clients and 375px for phones, and lists any render warnings. Download the HTML or copy it into your email provider.
The document is plain JSON, and the renderer returns HTML, a plain-text version and warnings. The demo shows all four live for whatever issue is open.
![]() |
![]() |
| The brand kit restyles every block at once. | New issues start from a template, for any period. |
![]() |
![]() |
flowchart LR
subgraph app["Your app"]
records[("Your records<br/>events · members · posts")]
store[("Your storage<br/>issues · templates · brand kit")]
end
records -- "DataSource.items()" --> editor["NewsletterEditor"]
editor -- "onChange(document)" --> store
store -- "NewsletterDocument (JSON)" --> render["renderEmail()"]
render --> email["HTML + plain text + warnings"]
email --> provider["Your email provider"]
A newsletter is a plain JSON NewsletterDocument: a subject, a preheader, the dates it covers and
an ordered list of blocks. Data-filled blocks store a snapshot of what they show, tagged with the
source's ids, so rendering never needs a database and refreshing is always explicit.
| Package | What it is |
|---|---|
@subterra-technologies/blockletter |
Document model, block registry, renderer, brand kit, templates, data sources. No dependencies. |
@subterra-technologies/blockletter-react |
The editor and every part of it, with one compiled, scoped stylesheet. |
apps/playground |
The demo site, and the browser tests that keep the editor accessible. |
Install both packages; the core alone is enough to render emails on a server:
npm install @subterra-technologies/blockletter @subterra-technologies/blockletter-reactBoth packages are ES modules only, for bundlers and modern Node (import, not require). The
editor needs React 19.2 or newer; the core runs anywhere JavaScript does, with no dependencies.
To see every piece below working together in an app, start from one of the examples: a Node script, a Next.js app, and a Convex backend with a React client.
import { NewsletterEditor } from '@subterra-technologies/blockletter-react';
import '@subterra-technologies/blockletter-react/styles.css';
export function IssueEditor({ issue, brand, onSave, onSaveBrand }) {
const [doc, setDoc] = useState(issue);
return (
<NewsletterEditor
fill // take the container's height, each pane scrolling on its own
value={doc}
onChange={setDoc}
brand={brand}
onBrandChange={onSaveBrand} // shows the Brand kit tab
sources={[eventsSource, postsSource]}
uploadImage={uploadToYourStorage} // (file) => Promise<{ url }>
renderOptions={{ baseUrl: 'https://example.org' }}
toolbar={<button onClick={() => onSave(doc)}>Save draft</button>}
/>
);
}With fill, the editor fits whatever height its container has (calc(100dvh - 4rem) under a
4rem header, say, or a flex item's share): its top bar stays put and each pane scrolls on its own,
as in the demo. Where it is narrower than 64rem it shows one pane at a time, switched from its top
bar. Leave fill out and the editor grows with the issue instead, scrolling with your page.
The editor keeps its own undo history of the documents it hands to onChange, so pass them back as
value (a copy read back from your database is fine). A document it did not hand out, such as
another issue or a reload, starts the history afresh.
The stylesheet is compiled and scoped to the editor, so your app needs no CSS framework or setup of its own. Every part (canvas, palette, inspector, preview, brand kit, template picker, dialogs) is also exported on its own for custom layouts.
import type { DataSource } from '@subterra-technologies/blockletter';
export const eventsSource: DataSource<'event_tiles'> = {
id: 'events',
label: 'Our events',
blockType: 'event_tiles',
async items({ period }) {
const events = await db.events.upcoming({ after: period?.end, until: period?.lookaheadEnd });
return events.map((event) => ({
ref: event.id, // your id, so a refresh knows which items came from you
title: event.title,
date: event.date, // 'YYYY-MM-DD' in your time zone
time: event.startsAt, // '6:30 PM'
location: event.venue,
url: `/events/${event.slug}`,
}));
},
};Start an issue from a template and every block that names a source is filled in:
import { assembleDocument, BUILT_IN_TEMPLATES } from '@subterra-technologies/blockletter';
const issue = await assembleDocument(BUILT_IN_TEMPLATES[0], {
period: { start: '2026-11-01', end: '2026-11-30', lookaheadEnd: '2027-01-11' },
brand: myBrandKit,
sources: [eventsSource, postsSource, sponsorsSource],
});import { renderEmail } from '@subterra-technologies/blockletter';
const { html, text, warnings } = renderEmail(issue, {
brand: myBrandKit,
baseUrl: 'https://example.org', // relative links in the issue resolve against this
unsubscribeUrl: '{{unsubscribe_url}}', // inserted verbatim: use your provider's merge tag
});
if (warnings.length) console.warn(warnings); // for example, an image with no alt text
await yourEmailProvider.send({ from, to, subject: issue.subject, html, text });A block is a definition (its fields, defaults, validation and email HTML) plus, for the editor, an icon and a form. The built-in blocks are written exactly this way.
import { blockValidator, defineBlock, type BlockBase } from '@subterra-technologies/blockletter';
interface JobBlock extends BlockBase<'job'> {
title: string;
location: string;
url: string;
}
export const jobBlock = defineBlock<JobBlock>({
type: 'job',
label: 'Job opening',
description: 'A role you are hiring for, with an apply button.',
group: 'content',
create: () => ({ title: 'Full stack developer', location: 'Remote', url: '/careers' }),
validate: (block, path) =>
blockValidator(block, path, 'job').string('title').string('location').string('url').issues,
render(block, ctx) {
ctx.text(block.title.toUpperCase(), block.location, `Apply: ${ctx.url(block.url)}`, '');
return ctx.section(
block,
ctx.heading(block.title, { size: 20 }) +
`<p style="${ctx.bodyStyle()}">${ctx.escape(block.location)}</p>` +
ctx.button('Apply', block.url),
);
},
});import {
builtInEditorBlocks,
defineEditorBlock,
EditorFields,
TextField,
} from '@subterra-technologies/blockletter-react';
import { BriefcaseIcon } from 'lucide-react';
const jobEditorBlock = defineEditorBlock<JobBlock>({
...jobBlock,
icon: BriefcaseIcon,
Editor: ({ block, onChange, readOnly }) => (
<EditorFields readOnly={readOnly}>
<TextField
label="Title"
value={block.title}
onChange={(title) => onChange({ ...block, title })}
/>
<TextField
label="Location"
value={block.location}
onChange={(location) => onChange({ ...block, location })}
/>
<TextField
label="Apply link"
value={block.url}
onChange={(url) => onChange({ ...block, url })}
/>
</EditorFields>
),
});
<NewsletterEditor definitions={[...builtInEditorBlocks, jobEditorBlock]} /* … */ />;
// and wherever you render: renderEmail(doc, { definitions: [...builtInBlocks, jobBlock] })A block without a canvas drawing of its own is drawn on the canvas from its email HTML. For free
text with formatting, render it with ctx.markdown(block.body) (HTML, and lines for ctx.text),
edit it in a MarkdownField, and draw it with EmailMarkdown, as the built-in blocks do.
To draw a built-in block your own way and keep its fields, validation and form, override the parts
you need. The new render is handed the original as base, so it can keep its plain-text lines:
import {
builtInBlocks,
footerBlock,
overrideBlock,
type FooterBlock,
type OverrideRender,
} from '@subterra-technologies/blockletter';
import {
builtInEditorBlocks,
overrideEditorBlock,
type EditorBlockDefinition,
} from '@subterra-technologies/blockletter-react';
const render: OverrideRender<FooterBlock> = (block, ctx, base) => {
base(block, ctx); // the plain-text lines; its HTML is not used
return ctx.section(block, `<p style="${ctx.smallStyle()}">${ctx.escape(ctx.brand.name)}</p>`);
};
const footer = overrideBlock(footerBlock, { render });
const footerEditor = overrideEditorBlock(
builtInEditorBlocks.find((d) => d.type === 'footer') as EditorBlockDefinition<FooterBlock>,
{ render },
);
renderEmail(doc, { definitions: [...builtInBlocks, footer] });
<NewsletterEditor definitions={[...builtInEditorBlocks, footerEditor]} /* … */ />;A later definition of a type replaces an earlier one. With a new render and no Canvas, the
editor draws the block from its new email HTML, so the canvas shows what will be sent.
Three small apps in examples/ use Blockletter the way yours would, each with its own
README:
- Node script: this month's issue assembled from a built-in template and a
JSON file of events, rendered to HTML and plain text, and sent through Resend's REST API with
fetch. - Next.js: the App Router with a drafts list, the editor filling the screen, drafts saved by Server Actions, a data source served by a route handler, and a Send a test action that renders on the server.
- Convex: issues assembled inside a mutation and validated before they are saved, the editor's data source as a query, and an action that renders and sends, with a small Vite + React client.
Each is its own npm project: npm install in its folder gets the published packages. To try an
example against a change you are making to the packages, install it against tarballs packed from
this repository, which hold exactly what npm would publish:
npm run examples:pack # build both packages and pack them into examples/.packs
npm run examples:install # install every example against themInstalling an example explains how, and why the examples keep their published version ranges throughout.
Every word the editor shows or says comes from one typed object, EditorMessages: labels and
buttons, tooltips, placeholders, toasts, what it announces to screen readers, its dialogs and its
error messages. The English is exported as enMessages. Pass what you translate as messages,
group by group, and whatever you leave out stays English. A message with values in it is a
function, so the word order and the plural forms are yours:
import type { RenderLabels } from '@subterra-technologies/blockletter';
import {
NewsletterEditor,
type EditorMessageOverrides,
} from '@subterra-technologies/blockletter-react';
// Defined once, outside the component: the editor reads it on every render.
const es: EditorMessageOverrides = {
topBar: { view: 'Vista', canvas: 'Lienzo', preview: 'Vista previa', more: 'Más' },
palette: {
heading: 'Bloques',
// The last argument writes numbers and dates the way `locale` does.
blocksUsed: (count, max, { number }) => `${number(count)} de ${number(max)} bloques`,
groups: { content: 'Contenido', layout: 'Diseño', graphics: 'Gráficos' },
},
history: {
undo: 'Deshacer',
redo: 'Rehacer',
undid: (action) => `Deshecho: ${action}.`,
deleted: (block) => `se eliminó el bloque ${block}`,
},
toasts: { deleted: (block) => `${block} eliminado.`, undo: 'Deshacer' },
blocks: {
text: { label: 'Texto', description: 'Un título y unos párrafos.' },
quote: { label: 'Cita', description: 'Una cita destacada, con su autor.' },
},
};
// The email's own words, which the canvas and the preview show as the inbox will.
const labels: Partial<RenderLabels> = {
readMore: 'Leer más',
managePreferences: 'Preferencias',
unsubscribe: 'Darse de baja',
months: 'ene. feb. mar. abr. may. jun. jul. ago. sept. oct. nov. dic.'.split(' '),
};
<NewsletterEditor
messages={es}
locale="es"
renderOptions={{ lang: 'es', labels }} // and the same to renderEmail() when you send
/* value, onChange, brand… */
/>;Two sets of words meet in the editor, and they need not be in the same language: someone can write a Spanish newsletter in an English editor.
| Words | Where they come from |
|---|---|
| The editor's own: buttons, tabs, forms, toasts, announcements | messages, over enMessages |
| The email's: "Read more", "Unsubscribe", month names on event tiles | renderOptions.labels, for the canvas and the preview |
| The issue's: its subject, its blocks' text, a new block's sample words | The document, your block definitions and your templates |
locale is the language of your messages, as a BCP 47 tag. The editor sets it as its lang, so
screen readers pronounce its words in that language, and uses it with Intl for the numbers and
dates it writes itself, such as an event's date in a data source's list; every function message
gets the same formatting as its last argument. Without a locale, the editor writes them as it
always has.
- Custom layouts. Every part reads its words from the nearest
BlockletterRoot, which takesmessagesandlocaletoo. A root inside another (NewsletterEditorwithin your own) starts from the outer one's. - Block names. The built-in blocks are named from
blocks(blocks.event_tiles.label). Your own blocks bring their ownlabelanddescription, and a built-in you give a label of your own keeps it. - Core's sentences. A block's warnings ("Add alt text…"), the renderer's warnings, the brand
kit's validation errors and a period's errors come from core with stable codes, which the editor
words from
issues,warnings,brandKit.errorsandperiod.errors. Your own UI can do the same withblockIssueDetails(),renderEmail().warningDetails,periodErrorCodes()and thecodeandvaluesof eachValidationIssue. - What stays yours. A data source's label, a template's name, the sample words a new block
starts with (its definition's
create), and the message of any error your callbacks throw are shown as you give them.
The repository's tests render the editor in a pseudo-locale, where every message is wrapped in markers, and fail on any word on screen, in a tooltip or in an accessible name that is not.
A document is plain JSON, so a program in any language, or a language model, can write one. The
core package ships JSON Schemas (draft-07) generated from its TypeScript types, with each type's
and field's documentation as its description:
| Schema | Import |
|---|---|
| Newsletter document | @subterra-technologies/blockletter/schema/newsletter-document.json |
| Newsletter template | @subterra-technologies/blockletter/schema/newsletter-template.json |
| Brand kit | @subterra-technologies/blockletter/schema/brand-kit.json |
A schema checks shape: block types, required fields, field types, colours and dates. It also
rejects properties the types do not declare, so a misspelt field is caught. A document that
matches the schema must still pass validateDocument() where your app stores or renders it.
That function is the source of truth for the rules the schema leaves out: the 30-block and
5,000-character limits, how many items each list block takes, unique block ids, real calendar
dates and safe image addresses. validateBrandKit() does the same for brand kits.
import { validateDocument } from '@subterra-technologies/blockletter';
import schema from '@subterra-technologies/blockletter/schema/newsletter-document.json' with { type: 'json' };
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });
const matchesSchema = ajv.compile(schema);
if (!matchesSchema(input)) throw new Error(ajv.errorsText(matchesSchema.errors));
const issues = validateDocument(input); // [] once it is ready to renderTo have a model write an issue, give it the schema as a structured-output response format (or as a tool's input schema), check its reply the same way, and send any issues back for it to fix:
// The response format OpenAI-compatible chat APIs take; `model` is whichever one you use.
const request = {
model,
messages: [{ role: 'user', content: "Write this month's issue for a community garden club." }],
response_format: {
type: 'json_schema',
json_schema: { name: 'newsletter_document', schema },
},
};The schema is shaped for these APIs: the root is an object, every object sets
additionalProperties: false, no $ref carries keywords of its own, and constants are one-value
enums. Their strict, grammar-enforced modes take only part of JSON Schema, though, and a whole
document is past some of their limits: some need every property to be required, and some cap how
many may be optional, where a document has dozens. So for a whole document, pass the schema
where it guides the model rather than binds it (a response format with strict mode off, or a
tool's input schema), and let the checks above catch what it gets wrong.
If your app registers blocks of its own, add a definition for each to the schema's definitions
and list it in definitions.BuiltInBlock.anyOf.
| Group | Block | What it is |
|---|---|---|
| Content | Header | Logo (three sizes) or name over a "title · issue" strapline |
| Letter | A personal note with a photo and a signature | |
| Text | A heading and a few paragraphs | |
| Event tiles ⚡ | Up to four upcoming events as big date tiles | |
| Name list ⚡ | A numbered list of names, such as new members | |
| Sponsors ⚡ | A logo and a thank-you note for each sponsor | |
| Post list ⚡ | Up to three recent posts, each linking out | |
| Article | A short feature article with an image beside it | |
| Dated list ⚡ | Dated lines for a community calendar | |
| Callout | A short heading, a sentence or two and a button | |
| Footer | Contact, website, links and the opt-out line; on a band or light | |
| Layout | Columns | Two or three side-by-side cards |
| Image + text | A picture beside a short story, with an optional link | |
| Button | A solid or outline button with a link | |
| Divider · Spacer | A rule between sections; breathing room | |
| Graphics | Banner | A wide hero image with a headline over or under it |
| Image · Photo grid | A full-width picture; two to six captioned photos | |
| Quote · Numbers | A pull quote in large type; two to four big figures |
⚡ can be filled by a data source. Every block also takes its own background, text colour, alignment, padding, font size, full-width band and divider.
The editor is built to WCAG 2.2 AA. The demo's browser tests run an automated accessibility audit at four widths on every change, and nothing scrolls sideways at 320px.
| Key | On the canvas |
|---|---|
| ↑ or ↓ | Move between blocks |
| Home or End | First or last block |
| Enter | Edit the focused block in the inspector |
| Alt + ↑ or Alt + ↓ | Move the focused block: the keyboard path for dragging |
| Toolbar: Insert above / below | Set an insertion point, then pick a block in the palette |
| Esc | Cancel the insertion point |
Anywhere in the editor, Ctrl + Z undoes and Ctrl + Shift + Z or Ctrl + Y redoes; on a Mac, ⌘ + Z and ⌘ + Shift + Z. In a text block's text, and in every free-text field with a formatting toolbar, Ctrl or ⌘ with B, I and K make words bold, italic or a link. Insertions, moves, refreshes, undos and redos are announced to screen readers, focus follows the work (to the inspector when a block is picked, back to the canvas when a dialog closes), and the brand kit warns when a colour pair is too faint to read.
git clone https://github.com/Subterra-Technologies/blockletter.git
cd blockletter
npm install
npm run dev # the demo at http://localhost:5173
npm test # unit and component tests, every package
npm run test:e2e # the demo in a real browser, with an accessibility audit
npm run check # denylist, lint, typecheck, tests, buildRequires Node 22+. The packages import each other's source inside the repository, so there is no
build step while you work. node apps/playground/scripts/capture-media.mjs regenerates the
screenshots and animations in this README from a running build of the demo.
After changing a type in packages/core/src/types.ts, run npm run schema -w packages/core to
regenerate the JSON Schemas (it runs TypeScript directly, so it needs Node 22.18 or newer); the
tests fail while a committed schema is stale.
Issues and pull requests are welcome. Read CONTRIBUTING.md first, follow the code of conduct, and report security problems privately as described in SECURITY.md. Questions and ideas belong in Discussions; issues labelled good first issue are a good place to start.
MIT. Built and maintained by Subterra Technologies.










