What is a ProseMirror command and how to implement one
masterIn ProseMirror, a command is a function that implements an editing action (e.g., triggered by a keypress or menu interaction).
Interface
A command typically follows this signature:
function(state, dispatch, view): boolean
state: The currentEditorState.dispatch: An optional function that takes a transaction (e.g.,view.dispatch). Ifdispatchis not provided (passed asnull), the command should only check if it is applicable and returntrueorfalsewithout performing any action. This allows you to query command applicability (e.g., for graying out menu items) without executing them.view: An optional third argument representing theEditorView, used if the command needs to interact with the DOM.
Implementation Rules
- Applicability: If the command cannot be performed in the current state, return
falseand do nothing. - Execution: If the command is applicable, dispatch a transaction and return
true. - Side Effects: While most commands dispatch transactions, they can also perform side effects like opening dialogs.
To check if a command is applicable: command(view.state, null)
To execute a command: command(view.state, view.dispatch)
// A standard command implementation
function deleteSelection(state, dispatch) {
if (state.selection.empty) return false
if (dispatch) dispatch(state.tr.deleteSelection())
return true
}
// Example of a command using the view for side effects
function blinkView(_state, dispatch, view) {
if (dispatch) {
view.dom.style.background = "yellow"
setTimeout(() => view.dom.style.background = "", 1000)
}
return true
}