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

43 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-11-05 05:38:52 +08:00
import { liftTarget } from 'prosemirror-transform'
2021-02-17 01:36:37 +08:00
import { Command, RawCommands } from '../types'
2020-11-05 05:38:52 +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
clearNodes: {
/**
* Normalize nodes to a simple paragraph.
*/
clearNodes: () => Command,
}
2021-02-11 01:05:02 +08:00
}
}
2021-02-17 01:36:37 +08:00
export const clearNodes: RawCommands['clearNodes'] = () => ({ state, tr, dispatch }) => {
2020-11-05 05:38:52 +08:00
const { selection } = tr
2021-03-29 03:30:47 +08:00
const { ranges } = selection
2020-11-05 05:38:52 +08:00
2021-03-29 03:30:47 +08:00
ranges.forEach(range => {
state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
if (!node.type.isText) {
const fromPos = tr.doc.resolve(tr.mapping.map(pos + 1))
const toPos = tr.doc.resolve(tr.mapping.map(pos + node.nodeSize - 1))
const nodeRange = fromPos.blockRange(toPos)
2020-11-05 05:38:52 +08:00
2021-03-29 03:30:47 +08:00
if (nodeRange) {
const targetLiftDepth = liftTarget(nodeRange)
2020-11-05 05:38:52 +08:00
2021-03-29 03:30:47 +08:00
if (node.type.isTextblock && dispatch) {
tr.setNodeMarkup(nodeRange.start, state.doc.type.contentMatch.defaultType)
}
2020-11-05 05:38:52 +08:00
2021-03-29 03:30:47 +08:00
if ((targetLiftDepth || targetLiftDepth === 0) && dispatch) {
tr.lift(nodeRange, targetLiftDepth)
}
2020-11-05 05:38:52 +08:00
}
}
2021-03-29 03:30:47 +08:00
})
2020-11-05 05:38:52 +08:00
})
return true
}