refactoring

This commit is contained in:
Philipp Kühn 2021-12-13 14:17:52 +01:00
parent 113133b74d
commit 9e6fbd6c88
2 changed files with 23 additions and 15 deletions

View File

@ -16,15 +16,20 @@ export const clearNodes: RawCommands['clearNodes'] = () => ({ state, tr, dispatc
const { selection } = tr const { selection } = tr
const { ranges } = selection const { ranges } = selection
ranges.forEach(range => { if (!dispatch) {
state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { return true
}
ranges.forEach(({ $from, $to }) => {
state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
if (node.type.isText) { if (node.type.isText) {
return return
} }
const $fromPos = tr.doc.resolve(tr.mapping.map(pos)) const { doc, mapping } = tr
const $toPos = tr.doc.resolve(tr.mapping.map(pos + node.nodeSize)) const $mappedFrom = doc.resolve(mapping.map(pos))
const nodeRange = $fromPos.blockRange($toPos) const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize))
const nodeRange = $mappedFrom.blockRange($mappedTo)
if (!nodeRange) { if (!nodeRange) {
return return
@ -32,13 +37,13 @@ export const clearNodes: RawCommands['clearNodes'] = () => ({ state, tr, dispatc
const targetLiftDepth = liftTarget(nodeRange) const targetLiftDepth = liftTarget(nodeRange)
if (node.type.isTextblock && dispatch) { if (node.type.isTextblock) {
const { defaultType } = $fromPos.parent.contentMatchAt($fromPos.index()) const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())
tr.setNodeMarkup(nodeRange.start, defaultType) tr.setNodeMarkup(nodeRange.start, defaultType)
} }
if ((targetLiftDepth || targetLiftDepth === 0) && dispatch) { if (targetLiftDepth || targetLiftDepth === 0) {
tr.lift(nodeRange, targetLiftDepth) tr.lift(nodeRange, targetLiftDepth)
} }
}) })

View File

@ -24,14 +24,17 @@ export const setNode: RawCommands['setNode'] = (typeOrName, attributes = {}) =>
return false return false
} }
const canSetBlock = setBlockType(type, attributes)(state)
if (canSetBlock) {
return setBlockType(type, attributes)(state, dispatch)
}
return chain() return chain()
.clearNodes() // try to convert node to default node if needed
.command(({ commands }) => {
const canSetBlock = setBlockType(type, attributes)(state)
if (canSetBlock) {
return true
}
return commands.clearNodes()
})
.command(({ state: updatedState }) => { .command(({ state: updatedState }) => {
return setBlockType(type, attributes)(updatedState, dispatch) return setBlockType(type, attributes)(updatedState, dispatch)
}) })