tiptap/packages/core/src/commands/replaceRange.ts

37 lines
879 B
TypeScript
Raw Normal View History

2021-01-21 03:37:53 +08:00
import { NodeType } from 'prosemirror-model'
import getNodeType from '../helpers/getNodeType'
2021-02-10 16:59:35 +08:00
import {
Command,
Commands,
Range,
AnyObject,
} from '../types'
2021-01-21 03:37:53 +08:00
2021-02-11 01:05:02 +08:00
declare module '@tiptap/core' {
2021-02-16 18:27:58 +08:00
interface AllCommands {
replaceRange: {
/**
* Replaces text with a node within a range.
*/
replaceRange: (range: Range, typeOrName: string | NodeType, attributes?: AnyObject) => Command,
}
2021-02-11 01:05:02 +08:00
}
}
2021-02-10 16:59:35 +08:00
export const replaceRange: Commands['replaceRange'] = (range, typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2021-01-21 03:37:53 +08:00
const type = getNodeType(typeOrName, state.schema)
const { from, to } = range
const $from = tr.doc.resolve(from)
const index = $from.index()
if (!$from.parent.canReplaceWith(index, index, type)) {
return false
}
if (dispatch) {
tr.replaceWith(from, to, type.create(attributes))
}
return true
}