# Rich text

The shape of a rich text field, and how to turn it into plain text, HTML or your own output with @mojimoto/richtext.

A `rich_text` field is delivered as JSON, not HTML. It is an ordered array of blocks, each with plain `text` and a list of `spans` that say where bold, italic and links apply. `@mojimoto/richtext` holds the types for that shape and three functions that read it: `asText`, `asHTML` and `serialize`.

The [React](/docs/frameworks/react) and [Vue](/docs/frameworks/vue) components are built on this package. Use it directly when you need a string: a meta description, an RSS feed, an email, a search index.

```bash
npm i @mojimoto/richtext
```

It has no dependencies. This page describes version 0.2.1.

## The shape of a rich text field

```json
[
  { "type": "heading2", "text": "Opening hours", "spans": [] },
  {
    "type": "paragraph",
    "text": "We are open every day. See the map.",
    "spans": [
      { "start": 12, "end": 21, "type": "strong" },
      { "start": 23, "end": 34, "type": "hyperlink", "data": { "link_type": "Web", "url": "https://example.com/map" } }
    ]
  },
  { "type": "list-item", "text": "Monday to Friday, 9 to 5", "spans": [] },
  { "type": "list-item", "text": "Weekends, 10 to 4", "spans": [] }
]
```

`start` and `end` are positions in `text`, counted in UTF-16 code units, the same way JavaScript indexes a string. `end` is exclusive, so `text.slice(start, end)` is the formatted part. Spans can nest (a bold link) but do not partly overlap.

An empty field is `null`, or missing from `data` if it was never filled in. Every function on this page accepts `null` and `undefined`.

### Block types

| `type` | Carries | Renders as |
| --- | --- | --- |
| `paragraph` | `text`, `spans` | `p` |
| `heading1` to `heading6` | `text`, `spans` | `h1` to `h6` |
| `preformatted` | `text`, `spans` | `pre`, with the text only |
| `list-item` | `text`, `spans` | `li`. Items in a row share one `ul` |
| `o-list-item` | `text`, `spans` | `li`. Items in a row share one `ol` |
| `image` | `url`, optional `alt`, `copyright`, `dimensions`, `linkTo` | `img` |
| `table` | `rows`, each `{ cells }`, each cell `{ text, spans, header }` | `table` |
| `embed` | `oembed`, with `html` and `embed_url` | the provider's HTML in a `div` |

Lists do not nest. A `\n` inside `text` is a soft line break. In a table, leading rows whose cells all have `header: true` become the `thead`.

### Span types

| `type` | `data` | Renders as |
| --- | --- | --- |
| `strong` | none | `strong` |
| `em` | none | `em` |
| `hyperlink` | a link, see below | `a` |
| `label` | `{ "label": "name" }` | `span` with that class |

A link is `{ "link_type": "Web", "url": "..." }`, with an optional `target`. A link to another entry is `{ "link_type": "Document", "id": 42, "uid": "about", "type": "page" }` and has no URL of its own.

> **Note:** The editor writes paragraphs, headings, preformatted text, lists, images, tables, bold, italic and web links. `embed` blocks, `label` spans and document links only arrive through the [Management API](/docs/api/management) or an [import](/docs/tools/importing-from-prismic). They are delivered as stored, but the editor cannot show them, and saving the entry there keeps their text and drops the rest.

## Get plain text

`asText` joins the text of every block. Blocks with no text, such as images, are skipped.

```ts
import { asText } from '@mojimoto/richtext'

asText(post.data.body)
// "Opening hours\nWe are open every day. See the map.\nMonday to Friday, 9 to 5\nWeekends, 10 to 4"

asText(post.data.body, { separator: ' ' })
```

| Option | Type | Description |
| --- | --- | --- |
| `separator` | `string` | Placed between blocks. Defaults to `"\n"`. |

Table cells are joined with a tab, and rows with the separator.

## Render HTML

```ts
import { asHTML } from '@mojimoto/richtext'

const html = asHTML(post.data.body)
```

```text output
<h2>Opening hours</h2><p>We are open <strong>every day</strong>. <a href="https://example.com/map">See the map</a>.</p><ul><li>Monday to Friday, 9 to 5</li><li>Weekends, 10 to 4</li></ul>
```

| Option | Type | Description |
| --- | --- | --- |
| `linkResolver` | `(link) => string` | Turns a document link into an `href`. |
| `components` | `MojiRichTextComponents<string>` | Your own HTML for any block or span. |

What the built-in output does:

- Text is escaped, and a `\n` becomes `br`.
- A link with `target: "_blank"` gets `rel="noopener noreferrer"`.
- An image is wrapped in `figure`, and in a link when it has `linkTo`.
- A document link has an empty `href` unless you pass a `linkResolver`.

```ts
asHTML(post.data.body, {
  linkResolver: (link) => (link.type === 'post' ? `/blog/${link.uid}` : `/${link.uid}`),
})
```

> **Warning:** An `embed` block's `oembed.html` is written out as it is, not escaped. If embeds can come from somewhere you do not trust, override `embed`.

## Change the HTML for one node

Pass `components` with only the entries you want to change. Each one returns a string. `children` is the inner HTML, already rendered, as an array of strings.

```ts
import { asHTML, escapeHTML } from '@mojimoto/richtext'

const html = asHTML(post.data.body, {
  components: {
    heading2: ({ children }) => `<h2 class="section-title">${children.join('')}</h2>`,
    image: ({ node }) => `<img src="${escapeHTML(node.url)}" alt="${escapeHTML(node.alt ?? '')}" loading="lazy">`,
  },
})
```

`escapeHTML(value)` escapes `&`, `<`, `>` and both quote characters. Use it on anything you place in the string yourself.

| Entry | Receives |
| --- | --- |
| `paragraph`, `heading1` to `heading6`, `preformatted`, `listItem`, `oListItem` | `{ node, children, key }` |
| `list`, `oList` | `{ children, key }`, the children being the items |
| `image`, `embed` | `{ node, key }` |
| `table` | `{ node, head, body, key }` |
| `tableRow`, `tableCell` | `{ node, children, key }` |
| `strong`, `em`, `label`, `hyperlink` | `{ node, children, key }`, the node being the span |
| `text` | `{ text, key }`, a run of unformatted text |

## Build your own renderer

`serialize` is what `asHTML` and the React and Vue components are built on. It walks the blocks, groups list items, nests the spans and calls your function for each node, innermost first. It returns one value per top-level block, of whatever type your functions return. A serializer must have every entry in the table above.

```ts
import { serialize, type MojiLink, type MojiRichTextSerializer } from '@mojimoto/richtext'

type Args = { children: string[] }

const block = ({ children }: Args) => `${children.join('')}\n\n`
const heading = (level: number) => ({ children }: Args) => `${'#'.repeat(level)} ${children.join('')}\n\n`

const toMarkdown: MojiRichTextSerializer<string> = {
  paragraph: block,
  heading1: heading(1),
  heading2: heading(2),
  heading3: heading(3),
  heading4: heading(4),
  heading5: heading(5),
  heading6: heading(6),
  preformatted: ({ node }) => `${node.text}\n\n`,
  list: ({ children }) => `${children.join('')}\n`,
  oList: ({ children }) => `${children.join('')}\n`,
  listItem: ({ children }) => `- ${children.join('')}\n`,
  oListItem: ({ children }) => `1. ${children.join('')}\n`,
  image: ({ node }) => `![${node.alt ?? ''}](${node.url})\n\n`,
  embed: ({ node }) => `${node.oembed.embed_url ?? ''}\n\n`,
  table: ({ head, body }) => `${[...head, ...body].join('')}\n`,
  tableRow: ({ children }) => `| ${children.join(' | ')} |\n`,
  tableCell: ({ children }) => children.join(''),
  strong: ({ children }) => `**${children.join('')}**`,
  em: ({ children }) => `_${children.join('')}_`,
  label: ({ children }) => children.join(''),
  hyperlink: ({ node, children }) => `[${children.join('')}](${(node.data as MojiLink).url ?? ''})`,
  text: ({ text }) => text,
}

const markdown = serialize(post.data.body, toMarkdown).join('')
```

A block with a `type` the package does not know is passed to `paragraph`, so its text is never lost. A span with an unknown type is passed to `text`.

## How the React and Vue components use it

`MojiRichText` in [@mojimoto/react](/docs/frameworks/react) and [@mojimoto/vue](/docs/frameworks/vue) calls `serialize` with a serializer that returns elements instead of strings. Its `components` prop is the same partial map as above, and its `linkResolver` is the same function. Two things differ from `asHTML`:

- Image blocks go through `MojiImage` and links through `MojiLink`, with no `figure` around an image.
- Text is rendered as it is, so a soft line break only shows if the block has `white-space: pre-line` in your CSS.

## Types

| Type | What it is |
| --- | --- |
| `MojiRichText` | The field value, an array of `MojiRichTextNode`. |
| `MojiTextNode`, `MojiImageNode`, `MojiTableNode`, `MojiEmbedNode` | One block. `MojiTableRow` and `MojiTableCell` are the parts of a table. |
| `MojiSpan`, `MojiSpanType`, `MojiTextBlockType` | A span, and the unions of span and text block names. |
| `MojiLink`, `MojiLinkResolver` | A link value, and the function that turns one into an `href`. |
| `MojiRichTextSerializer<T>`, `MojiRichTextComponents<T>` | A full serializer, and a partial one. |
| `AsTextOptions`, `AsHTMLOptions` | The options above. |

The argument types are exported too: `BlockArgs`, `LeafArgs`, `ListArgs`, `TableArgs`, `TableRowArgs`, `TableCellArgs` and `TextRunArgs`.

> **Note:** [Generated types](/docs/tools/generated-types) type a rich text field as `unknown`, so cast it before you pass it on: `post.data.body as MojiRichText`.
