add updateMark command

This commit is contained in:
Philipp Kühn
2020-04-22 14:50:02 +02:00
parent bddd5b3da7
commit 4cfadf7d7f
3 changed files with 47 additions and 1 deletions

View File

@@ -47,3 +47,7 @@ Toggle a mark on and off.
## .toggleNode()
Toggle a node with another node.
## .updateMark()
Update a mark with new attributes.

View File

@@ -77,6 +77,7 @@ export class Editor extends EventEmitter {
this.registerCommand('setContent', require('./commands/setContent').default)
this.registerCommand('toggleMark', require('./commands/toggleMark').default)
this.registerCommand('toggleNode', require('./commands/toggleNode').default)
this.registerCommand('updateMark', require('./commands/updateMark').default)
if (this.options.injectCSS) {
require('./style.css')

View File

@@ -0,0 +1,41 @@
import { Editor } from '../Editor'
import { MarkType } from 'prosemirror-model'
import getMarkType from '../utils/getMarkType'
import getMarkRange from '../utils/getMarkRange'
type UpdateMark = (
type: string | MarkType,
attrs: {},
) => any
declare module '../Editor' {
interface Editor {
updateMark: UpdateMark,
}
}
export default (next: Function, editor: Editor): UpdateMark => (typeOrName, attrs) => {
const { view, state, schema } = editor
const { tr, selection, doc } = state
let { from, to, $from, empty } = selection
const type = getMarkType(typeOrName, schema)
if (empty) {
const range = getMarkRange($from, type)
if (range) {
from = range.from
to = range.to
}
}
const hasMark = doc.rangeHasMark(from, to, type)
if (hasMark) {
tr.removeMark(from, to, type)
}
tr.addMark(from, to, type.create(attrs))
view.dispatch(tr)
next()
}