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

37 lines
981 B
TypeScript
Raw Normal View History

2020-11-18 04:38:15 +08:00
import { MarkType } from 'prosemirror-model'
2021-02-17 01:36:37 +08:00
import { AnyObject, Command, RawCommands } from '../types'
2020-11-30 16:42:53 +08:00
import getMarkType from '../helpers/getMarkType'
import getMarkAttributes from '../helpers/getMarkAttributes'
2020-11-18 04:38:15 +08:00
2021-02-11 01:05:02 +08:00
declare module '@tiptap/core' {
2021-02-17 01:39:37 +08:00
interface Commands {
2021-02-16 18:27:58 +08:00
setMark: {
/**
* Add a mark with new attributes.
*/
setMark: (typeOrName: string | MarkType, attributes?: AnyObject) => Command,
}
2021-02-11 01:05:02 +08:00
}
}
2021-02-17 01:36:37 +08:00
export const setMark: RawCommands['setMark'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2020-11-18 04:38:15 +08:00
const { selection } = tr
2020-11-18 18:05:19 +08:00
const { from, to, empty } = selection
2020-11-18 04:38:15 +08:00
const type = getMarkType(typeOrName, state.schema)
2020-11-18 18:05:19 +08:00
const oldAttributes = getMarkAttributes(state, type)
const newAttributes = {
...oldAttributes,
...attributes,
}
2020-11-18 04:38:15 +08:00
if (dispatch) {
2020-11-18 18:05:19 +08:00
if (empty) {
tr.addStoredMark(type.create(newAttributes))
} else {
tr.addMark(from, to, type.create(newAttributes))
}
2020-11-18 04:38:15 +08:00
}
return true
}