Skip to content

Your own extension ​

An extension is a factory made with defineExtension(). This one adds a highlight mark with a command, a shortcut and a Markdown-style input rule:

ts
import { type Command, createEditor } from '@writeon/core'
import { defineExtension, markInputRule } from '@writeon/core/extension'
import { basic } from '@writeon/core/presets'
import { toggleMark } from 'prosemirror-commands'

// Toggles the highlight mark.
// A factory, like every built-in command.
export function toggleHighlight(): Command {
  return (state, dispatch) => {
    const type = state.schema.marks.highlight
    return type ? toggleMark(type)(state, dispatch) : false
  }
}

// Typing ==text== highlights the text.
const doubleEquals = /(?:^|[^=])(==([^=\s](?:[^=]*[^=\s])?)==)$/

// Highlighted text: <mark> in HTML, Mod-Shift-h or ==text==.
export const highlight = defineExtension(() => ({
  name: 'highlight',

  marks: {
    highlight: {
      parseDOM: [{ tag: 'mark' }],
      toDOM: () => ['mark', 0],
    },
  },

  keymap: () => ({ 'Mod-Shift-h': toggleHighlight() }),

  inputRules: ({ schema }) => {
    const type = schema.marks.highlight
    return type ? [markInputRule(doubleEquals, type)] : []
  },
}))

const editor = createEditor({
  extensions: [...basic(), highlight()],
  label: 'Notes',
})
editor.run(toggleHighlight())

The parts of an extension:

FieldWhat it does
nameUnique; two extensions with the same name are an error
nodes, marksProseMirror node and mark specs added to the schema
keymap(ctx)Shortcuts to commands (Mod is Cmd on Apple, Ctrl elsewhere)
inputRules(ctx)Typed patterns that trigger changes
plugins(ctx)Any ProseMirror plugins
requiresNames of extensions that must also be present
priorityHigher runs first for keymaps and plugins (default 100)

Remember:

  • Add it on the server too, or validate() removes the new mark as unknown.
  • Commands are factories returning a command, like the built-in ones, so editor.run(toggleHighlight()) and editor.can(toggleHighlight()) read the same.
  • An extension with nodes or marks must be passed to createEditor(). editor.enable() only adds behaviour; for that, split the extension into a schema part and a behaviour part, like @writeon/advanced does.