add replaceRange command

This commit is contained in:
Philipp Kühn
2021-01-20 20:37:53 +01:00
parent 1880b43e37
commit 55d767d94c
5 changed files with 34 additions and 20 deletions

View File

@@ -1,24 +1,12 @@
import { NodeType } from 'prosemirror-model'
import getNodeType from '../helpers/getNodeType'
import { Command, Range, AnyObject } from '../types'
import { Command, AnyObject } from '../types'
/**
* Replaces text with a node within a range.
* Replaces text with a node.
*/
export const replace = (range: Range | null = null, typeOrName: string | NodeType, attrs: AnyObject = {}): Command => ({ tr, state, dispatch }) => {
const type = getNodeType(typeOrName, state.schema)
const { $from, $to } = state.selection
const index = $from.index()
const from = range ? range.from : $from.pos
const to = range ? range.to : $to.pos
export const replace = (typeOrName: string | NodeType, attributes: AnyObject = {}): Command => ({ state, commands }) => {
const { from, to } = state.selection
const range = { from, to }
if (!$from.parent.canReplaceWith(index, index, type)) {
return false
}
if (dispatch) {
tr.replaceWith(from, to, type.create(attrs))
}
return true
return commands.replaceRange(range, typeOrName, attributes)
}