tiptap/packages/core/src/extensions/updateMark.ts

46 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-10-23 16:44:30 +08:00
import { MarkType } from 'prosemirror-model'
import { Command } from '../Editor'
import { createExtension } from '../Extension'
import getMarkType from '../utils/getMarkType'
import getMarkRange from '../utils/getMarkRange'
export const UpdateMark = createExtension({
addCommands() {
return {
2020-11-02 23:23:43 +08:00
updateMark: (typeOrName: string | MarkType, attrs: {}): Command => ({ tr, state, dispatch }) => {
2020-10-23 16:44:30 +08:00
const { selection, doc } = tr
let { from, to } = selection
const { $from, empty } = selection
const type = getMarkType(typeOrName, state.schema)
if (empty) {
const range = getMarkRange($from, type)
if (range) {
from = range.from
to = range.to
}
}
const hasMark = doc.rangeHasMark(from, to, type)
2020-11-02 23:23:43 +08:00
if (hasMark && dispatch) {
2020-10-23 16:44:30 +08:00
tr.removeMark(from, to, type)
}
2020-11-02 23:23:43 +08:00
if (dispatch) {
tr.addMark(from, to, type.create(attrs))
}
2020-10-23 16:44:30 +08:00
return true
},
}
},
})
declare module '../Editor' {
interface AllExtensions {
UpdateMark: typeof UpdateMark,
}
}