I have a math node view which implements the following openEditor
method (i.e. after click on math node, the innerView
appears which enable me to edit content).
openEditor() {
if (this._innerView) {
throw Error("inner view should not exist!");
}
// create a nested ProseMirror view
this._innerView = new EditorView(this._mathSrcElt!, {
state: EditorState.create({
doc: this._node,
plugins: [
keymap({
Tab: (state, dispatch) => {
if (dispatch) {
dispatch(state.tr.insertText("\t"));
}
return true;
},
Backspace: chainCommands(
deleteSelection,
(state, dispatch, tr_inner) => {
// default backspace behavior for non-empty selections
if (!state.selection.empty) {
return false;
}
// default backspace behavior when math node is non-empty
if (this._node.textContent.length > 0) {
return false;
}
// otherwise, we want to delete the empty math node and focus the outer view
this._outerView.dispatch(
this._outerView.state.tr.insertText("")
);
this._outerView.focus();
return true;
}
),
"Ctrl-Backspace": (state, dispatch, tr_inner) => {
// delete math node and focus the outer view
this._outerView.dispatch(this._outerView.state.tr.insertText(""));
this._outerView.focus();
return true;
},
Enter: chainCommands(
newlineInCode,
collapseMathCmd(this._outerView, +1, false)
),
"Ctrl-Enter": collapseMathCmd(this._outerView, +1, false),
ArrowLeft: collapseMathCmd(this._outerView, -1, true),
ArrowRight: collapseMathCmd(this._outerView, +1, true),
ArrowUp: collapseMathCmd(this._outerView, -1, true),
ArrowDown: collapseMathCmd(this._outerView, +1, true),
"Ctrl-m": () => this.toggleMath(),
"Ctrl-d": () => this.toggleMath(),
}),
],
}),
dispatchTransaction: this.dispatchInner.bind(this),
});
// focus element
let innerState = this._innerView.state;
this._innerView.focus();
// request outer cursor position before math node was selected
let maybePos = this._mathPluginKey.getState(this._outerView.state)
?.prevCursorPos;
if (maybePos === null || maybePos === undefined) {
console.error(
"[prosemirror-math] Error: Unable to fetch math plugin state from key."
);
}
let prevCursorPos: number = maybePos ?? 0;
// compute position that cursor should appear within the expanded math node
let innerPos =
prevCursorPos <= this._getPos() ? 0 : this._node.nodeSize - 2;
this._innerView.dispatch(
innerState.tr.setSelection(TextSelection.create(innerState.doc, innerPos))
);
this._isEditing = true;
}
Here I implemented Ctrl-d
shortcut to remove math and insert its content as plain text. My menu bar contains a button which should toggle math but currently it can only insert math node to my document since I don’t know how can I call this.toggleMath()
(which is defined in my ndoe view and which is called when clicking Ctrl-d
) method on the current node. How can I somehow access this method or maybe imitate calling Ctrl-d
shortcut (which works fine)?