add replaceWithNode command

This commit is contained in:
Philipp Kühn
2020-04-22 14:38:15 +02:00
parent fd8f5de375
commit 9f53481e01
3 changed files with 40 additions and 0 deletions

View File

@@ -71,6 +71,7 @@ export class Editor extends EventEmitter {
this.registerCommand('insertText', require('./commands/insertText').default)
this.registerCommand('removeMark', require('./commands/removeMark').default)
this.registerCommand('removeMarks', require('./commands/removeMarks').default)
this.registerCommand('replaceWithNode', require('./commands/replaceWithNode').default)
this.registerCommand('selectAll', require('./commands/selectAll').default)
this.registerCommand('selectParentNode', require('./commands/selectParentNode').default)
this.registerCommand('setContent', require('./commands/setContent').default)

View File

@@ -0,0 +1,35 @@
import { Editor } from '../Editor'
import { NodeType } from 'prosemirror-model'
import getNodeType from '../utils/getNodeType'
interface Range {
from: number,
to: number,
}
type ReplaceWithNode = (
range: Range,
type: NodeType,
attrs: {},
) => any
declare module '../Editor' {
interface Editor {
replaceText: ReplaceWithNode,
}
}
export default (next: Function, editor: Editor): ReplaceWithNode => (range, typeOrName, attrs) => {
const { view, state, schema } = editor
const { $from, $to } = state.selection
const type = getNodeType(typeOrName, schema)
const index = $from.index()
const from = range ? range.from : $from.pos
const to = range ? range.to : $to.pos
if ($from.parent.canReplaceWith(index, index, type)) {
view.dispatch(state.tr.replaceWith(from, to, type.create(attrs)))
}
next()
}