Editors

JSails keeps the rich-text model and the editor separate. The model, RichTextDocument from jsails/rich-text, is what a store holds, what the renderer reads, and what search indexes. An editor is only a way to produce one: it loads a document, lets an author change it, and hands back a document. Nothing editor-specific is persisted, so replacing the editor never needs a data migration.

The model

A document is a version number and a list of blocks. Text lives in inline runs: each run is a string with optional marks (bold, italic, strike, code) and an optional link.

import { parseRichText } from 'jsails/rich-text';

const result = parseRichText({
  version: 2,
  blocks: [
    { type: 'heading', level: 2, content: [{ text: 'Release notes' }] },
    {
      type: 'paragraph',
      content: [
        { text: 'Read the ' },
        { text: 'upgrade guide', marks: ['bold'], href: '/docs/upgrading' },
        { text: ' first.' },
      ],
    },
    {
      type: 'list',
      style: 'task',
      items: [{ content: [{ text: 'Back up the database' }], checked: true }],
    },
  ],
});

The block kinds are paragraph, heading (levels 2 to 6), quote (with an optional citation), callout (info, success, warning, danger), code (with an optional language), list (ordered, unordered, or task, nested up to three levels), image and gallery (media-library ids), embed (an https: URL), cta (a label and a link), and divider. A \n in a run is a hard line break; headings, labels, alt text and captions hold none.

Links are accepted by isLinkHref: a same-origin path (/pricing, never //host), a fragment (#top), an http:// or https:// URL with a host and no userinfo, mailto: or tel:. Embeds are accepted by isEmbedUrl: an https:// URL with a host and no userinfo. Both are allowlists, so javascript:, data:, upper-case schemes, backslashes and whitespace are refused rather than repaired. Text may not hold control characters (except \n, and \t in code), bidi override or isolate characters, or unpaired surrogates.

A document also has a budget: 256 KiB of JSON (MAX_DOCUMENT_BYTES), 500 blocks (MAX_BLOCKS), 20 000 characters of text per block (MAX_BLOCK_CHARS), and 500 items per list (MAX_LIST_ITEMS). measureRichText(document) reports all four, so an editor can refuse an edit that would leave the budget.

Reading and writing

parseRichText(value) is the only reader of a stored or submitted document. It checks the version, the size, the schema, the budget, and that the document is already in canonical form, and returns { ok: true, value } or { ok: false, issues }. Each issue is a path and a code (invalid_link, not_canonical, too_large, ...); no issue ever repeats the offending text or URL. It never repairs a value.

Canonical form is the one spelling of a document's content: no empty runs, adjacent runs with the same marks and link merged, marks sorted and code alone when present, no empty optional fields, checked on every task item and on no other item, no empty list or gallery. A writer builds whatever schema-valid document is convenient and stores its canonical form:

import { normalizeRichText, parseRichText, type RichTextDocument } from 'jsails/rich-text';

function toStored(draft: RichTextDocument): RichTextDocument {
  const read = parseRichText(normalizeRichText(draft));
  if (!read.ok) {
    throw new Error('the document is over budget');
  }
  return read.value;
}

richTextToPlainText(document) is the text projection used for search and excerpts: every block's runs concatenated, list items one per line, code, alt text, captions, citations and button labels included, lines joined with \n. It is plain text, not HTML.

Upgrading stored documents

A document of any version other than the current one is refused by number. upgradeRichTextDocument(value) is the explicit path from version 1: it turns each version 1 text into one run, drops block ids, brings text within the current rules, turns a call to action or embed whose URL is now refused into a paragraph of its text, and returns the result of parseRichText on the normalised document. A current document passes through unchanged.

The blog ships this as a data migration. List it in the dataMigrations export of jsails.database.js and run npm run db:push:

import { blogRichTextUpgrade } from '@jsails/blog';

export const dataMigrations = { blogRichTextUpgrade };

Until it has run, reading a version 1 post or page fails with BlogContentError code unreadable_body. The migration upgrades post and page bodies and the bodies inside revision snapshots. It reads every row first and, if any body cannot be upgraded, fails with the count of such bodies and their row ids (jsails_blog_content_post#12, never their content) and writes nothing, so you can fix those rows by hand and push again. It runs on every push and is idempotent: once every body is current it only reads.

The admin field

An admin richText field stores a canonical RichTextDocument:

import { defineResource } from '@jsails/admin';

export const articles = defineResource({
  slug: 'articles',
  label: 'Articles',
  columns: [{ name: 'title', label: 'Title' }],
  fields: [
    { name: 'title', label: 'Title', type: 'text' },
    {
      name: 'body',
      label: 'Body',
      type: 'richText',
      mediaPickerUrl: '/admin/media?format=json',
    },
  ],
  list: async () => ({ rows: [], total: 0 }),
});

A submitted value is checked against the schema, normalised, and read with parseRichText, so the value a resource's save receives is always canonical and within budget; anything else is a validation error with value-free messages. blogAdmin uses the same field for post and page bodies.

The form renders a data-jsails-island="rich-text" marker. The editor island from @jsails/editor/preact hydrates it; register it in the app client entry:

import { startClient } from 'jsails/client';
import { richTextIsland } from '@jsails/editor/preact';

await startClient({ islands: richTextIsland });

The Editor.js island

The current island wraps Editor.js. It saves each text as one unmarked run, so bold, italic and links made with the inline toolbar are not kept yet; lists keep their nesting up to three levels, and an Editor.js checklist is a task list.

Every submit of the enclosing form waits for the editor to save its current content (Editor.js reports a change only after a short delay), then goes through with that content, so a submit right after a keystroke never sends the previous document. When the content has no valid rich-text form, or the save fails, the editor marks itself invalid (aria-invalid plus an alert), refuses the submit, and sets its hidden input to a value the field refuses, so the last valid document is never saved in place of what the author sees. A host that uses RichTextEditor without a form and saves on onChange receives onInvalid instead, and must not save until onChange fires again.

For image and gallery blocks, set mediaPickerUrl on the field. It must point at a same-origin JSON endpoint returning media assets; the generated blog uses /admin/media?format=json. The image and gallery tools fetch it with credentials: 'same-origin', send limit=50 and, when the search box has a term, q, read the paged envelope { assets, total }, render asset names as text, and write the selected id into the block. The fetched page is cached per picker instance, and filtering stays server-side. Without the option the tools fall back to manual media-id inputs.

Building your own editor

An editor is an island registered under the rich-text name, or under its own name on a page you render. It receives name (the form field) and document in data-jsails-props, and keeps a hidden input named after the field holding the JSON of the document the author sees. There is no adapter registry and no editor-native payload: the editor emits a RichTextDocument, and the server reads it with parseRichText. Normalise before emitting (normalizeRichText) and check measureRichText while editing, so the author never builds a document the server will refuse.

Rendering

renderRichText from @jsails/editor/server turns a document into HTML built from a fixed set of elements and attributes:

import { renderRichText } from '@jsails/editor/server';
import type { RichTextDocument } from 'jsails/rich-text';

declare const body: RichTextDocument;

const html = renderRichText(body, {
  resolveMedia: (mediaId) => ({ src: `/media/${encodeURIComponent(mediaId)}` }),
  embedHostAllowlist: ['.youtube.com', 'player.vimeo.com'],
});

Marks render as strong, em, s and code, links as <a> (with rel="noopener noreferrer" for an absolute URL), and a task list as a list of disabled checkboxes. The renderer reads its input with parseRichText and throws RichTextRenderError code invalid_document for a value it refuses, so a document that skipped the reader cannot reach the page. An embed whose host is not on the allowlist (empty by default) and a media id the resolver does not know render a placeholder.

Security

Every text and attribute value is escaped, and there is no raw-HTML block. Link and embed URLs are checked once, by the model's predicates, when a document is read; the renderer emits only what passed them. Client HTML is never trusted: an editor's output is a document, and a document holds text.