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:
| Field | What it does |
|---|---|
name | Unique; two extensions with the same name are an error |
nodes, marks | ProseMirror 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 |
requires | Names of extensions that must also be present |
priority | Higher 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())andeditor.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/advanceddoes.