Extensions

field

Node 0.55 kB gzipped

A blank in a template.

`{{name}}` in a letter is a promise that something will be put there, and as text it is a promise the editor cannot keep: it can be half-deleted into `{{nam}}`, spell-checked, bolded from the middle, and nothing will notice until the letter goes out with braces in it. As an atom it is one thing — the caret steps over it, backspace removes all of it — and filling it is a command rather than a search and replace.

`fillFields` fills the fields in the editor; `fillFieldsIn` does the same to a document as JSON, with no editor and no DOM, which is where a mail merge actually runs.

1 · Install

One package for every extension · there is no @matrajs/field to install.

npm i @matrajs/core

2 · Add it to the editor

Import it and put it in the extensions array. That array is the whole feature list: what is not in it is not in your bundle and not in the document's schema.

import { createEditor, document, paragraph, text, field } from '@matrajs/core'

const editor = createEditor({
  extensions: [document, paragraph, text, field],
  element: document.querySelector('#editor'),
})

3 · Use it

Run a command, and give focus back · a click on a button takes it away.

editor.commands.insertField('Untitled')
editor.focus()

Wired to a button, with the pressed state kept in step:

const button = document.querySelector('#insertField')

button.addEventListener('click', () => {
  editor.commands.insertField('Untitled')
  editor.focus()
})

const read = () => button.setAttribute('aria-pressed', String(editor.isActive('field')))
editor.on('selectionChange', read)
editor.on('change', read)
read()

Both events, not one. selectionChange covers the caret moving into it; change covers the command that changed it without moving anything. A toolbar wired to only the first goes stale the moment someone uses the keyboard.

Commands

Every one returns true if it changed the document and false if it could not · a command that does not apply where the caret is says so rather than throwing.

Command Call
insertField editor.commands.insertField(name: string, label?: string | null)
fillFields editor.commands.fillFields(values: Record<string, FieldValue>)

In the document

Attribute Default
name none
label none

← All 83 extensions

Edit this page on GitHub