Skip to content

Custom blocks ​

Some content is not text: a list of pickup branches, a product carousel, a map. Store it as a custom block (an embed) and let your front end render the component.

ts
import {
  embed,
  insertEmbed,
  updateEmbed,
} from '@writeon/advanced/embed'
import { createEditor } from '@writeon/core'
import { basic } from '@writeon/core/presets'

// The blocks your front end knows how to render.
export const extensions = [
  ...basic(),
  embed({
    kinds: [
      { id: 'pickup-branches', label: 'Pickup branches' },
      {
        id: 'product-list',
        label: 'Products',
        props: {
          category: {
            type: 'string',
            label: 'Category',
            required: true,
          },
          limit: {
            type: 'number',
            label: 'How many',
            integer: true,
            min: 1,
            max: 24,
            default: 8,
          },
        },
      },
    ],
  }),
]

const editor = createEditor({ extensions, label: 'Page' })

// Fails (returns false) while a required field is missing.
editor.run(insertEmbed('product-list', { category: 'drills' }))

// With the block selected: change its settings.
editor.run(updateEmbed({ category: 'saws', limit: 12 }))
  • The document stores { type: 'embed', attrs: { kind: 'product-list', props: { category: 'drills', limit: 8 } } }. The user cannot break it by typing: the editor shows it as a [[Products]] placeholder that can be selected, moved and deleted.
  • Your front end finds the block by kind, in the JSON or in the HTML from toHTML(): <div data-embed="product-list" data-props="{…}">[[Products]]</div>. Replace that element with the component; the [[Products]] text is the fallback without JavaScript.
  • Settings (props) are typed fields: string, number (with min, max, integer), boolean and enum (fixed options), each required or with a default. embedPropsError(kind, props) explains what is wrong, for your form.
  • On the server, validate() removes a block whose kind is not configured or whose props do not fit it (unknown fields, wrong types, a missing required field). Props are always a flat object of plain values.
  • Markdown: [[product-list {"category":"drills","limit":8}]] on its own line, read back by fromMarkdown().
  • UI: embedKinds(state) lists the kinds for your menu; selectedEmbed(state) gives the selected block for a settings form.