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

20 lines
646 B
TypeScript
Raw Normal View History

2020-11-05 05:38:52 +08:00
import { NodeType } from 'prosemirror-model'
2020-11-17 04:42:35 +08:00
import { Command } from '../types'
2020-12-01 16:11:58 +08:00
import isNodeActive from '../helpers/isNodeActive'
2020-11-30 16:42:53 +08:00
import getNodeType from '../helpers/getNodeType'
2020-11-05 05:38:52 +08:00
2020-11-18 23:43:27 +08:00
/**
* Toggle a node with another node.
*/
export const toggleNode = (typeOrName: string | NodeType, toggleTypeOrName: string | NodeType, attrs = {}): Command => ({ state, commands }) => {
2020-11-05 05:38:52 +08:00
const type = getNodeType(typeOrName, state.schema)
const toggleType = getNodeType(toggleTypeOrName, state.schema)
2020-12-01 16:11:58 +08:00
const isActive = isNodeActive(state, type, attrs)
2020-11-05 05:38:52 +08:00
if (isActive) {
2020-11-21 06:56:41 +08:00
return commands.setNode(toggleType)
2020-11-05 05:38:52 +08:00
}
2020-11-21 06:56:41 +08:00
return commands.setNode(type, attrs)
2020-11-05 05:38:52 +08:00
}