From 85c1a8ace9102521b4f15a0d466aa9259f64fd24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Ku=CC=88hn?= Date: Mon, 2 Nov 2020 12:45:19 +0100 Subject: [PATCH] add clearNodes command --- packages/core/src/extensions/clearNodes.ts | 42 ++++++++++++++++++++++ packages/core/src/extensions/index.ts | 1 + packages/core/src/extensions/toggleList.ts | 3 +- 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/extensions/clearNodes.ts diff --git a/packages/core/src/extensions/clearNodes.ts b/packages/core/src/extensions/clearNodes.ts new file mode 100644 index 000000000..5d7557676 --- /dev/null +++ b/packages/core/src/extensions/clearNodes.ts @@ -0,0 +1,42 @@ +import { liftTarget } from 'prosemirror-transform' +import { Command } from '../Editor' +import { createExtension } from '../Extension' + +export const ClearNodes = createExtension({ + addCommands() { + return { + clearNodes: (): Command => ({ state, tr }) => { + const { selection } = tr + const { from, to } = selection + + state.doc.nodesBetween(from, to, (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) + + if (nodeRange) { + const targetLiftDepth = liftTarget(nodeRange) + + if (node.type.isTextblock) { + tr.setNodeMarkup(nodeRange.start, state.schema.nodes.paragraph) + } + + if (targetLiftDepth || targetLiftDepth === 0) { + tr.lift(nodeRange, targetLiftDepth) + } + } + } + }) + + return true + }, + } + }, +}) + +declare module '../Editor' { + interface AllExtensions { + ClearNodes: typeof ClearNodes, + } +} diff --git a/packages/core/src/extensions/index.ts b/packages/core/src/extensions/index.ts index 453aa847a..d90067232 100644 --- a/packages/core/src/extensions/index.ts +++ b/packages/core/src/extensions/index.ts @@ -1,5 +1,6 @@ export { Blur } from './blur' export { ClearContent } from './clearContent' +export { ClearNodes } from './clearNodes' export { DeleteSelection } from './deleteSelection' export { Focus } from './focus' export { InsertHTML } from './insertHTML' diff --git a/packages/core/src/extensions/toggleList.ts b/packages/core/src/extensions/toggleList.ts index b9ed6f1a2..ccf302cee 100644 --- a/packages/core/src/extensions/toggleList.ts +++ b/packages/core/src/extensions/toggleList.ts @@ -44,7 +44,8 @@ export const ToggleList = createExtension({ // try to convert node to paragraph if needed if (!canWrapInList) { return chain() - .setBlockType('paragraph') + // .setBlockType('paragraph') + .clearNodes() .wrapInList(listType) .run() }