refactoring
This commit is contained in:
29
packages/core/src/commands/replace.ts
Normal file
29
packages/core/src/commands/replace.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { NodeType } from 'prosemirror-model'
|
||||
import getNodeType from '../helpers/getNodeType'
|
||||
import { Command } from '../types'
|
||||
|
||||
export type Range = {
|
||||
from: number,
|
||||
to: number,
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces text with a node within a range.
|
||||
*/
|
||||
export const replace = (range: Range | null = null, typeOrName: string | NodeType, attrs = {}): 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
|
||||
|
||||
if (!$from.parent.canReplaceWith(index, index, type)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (dispatch) {
|
||||
tr.replaceWith(from, to, type.create(attrs))
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import * as lift from '../commands/lift'
|
||||
import * as liftEmptyBlock from '../commands/liftEmptyBlock'
|
||||
import * as liftListItem from '../commands/liftListItem'
|
||||
import * as newlineInCode from '../commands/newlineInCode'
|
||||
import * as replace from '../commands/replace'
|
||||
import * as resetNodeAttributes from '../commands/resetNodeAttributes'
|
||||
import * as scrollIntoView from '../commands/scrollIntoView'
|
||||
import * as selectAll from '../commands/selectAll'
|
||||
@@ -63,6 +64,7 @@ export const Commands = Extension.create({
|
||||
...liftEmptyBlock,
|
||||
...liftListItem,
|
||||
...newlineInCode,
|
||||
...replace,
|
||||
...resetNodeAttributes,
|
||||
...scrollIntoView,
|
||||
...selectAll,
|
||||
|
||||
Reference in New Issue
Block a user