add figureToImage command

This commit is contained in:
Philipp Kühn
2021-06-04 23:58:00 +02:00
parent a757716f68
commit 6212cb46d1

View File

@@ -3,6 +3,7 @@ import {
nodeInputRule, nodeInputRule,
mergeAttributes, mergeAttributes,
findChildrenInRange, findChildrenInRange,
Tracker,
} from '@tiptap/core' } from '@tiptap/core'
export interface FigureOptions { export interface FigureOptions {
@@ -124,20 +125,24 @@ export const Figure = Node.create<FigureOptions>({
imageToFigure: () => ({ tr, commands }) => { imageToFigure: () => ({ tr, commands }) => {
const { doc, selection } = tr const { doc, selection } = tr
const { from, to } = selection const { from, to } = selection
const nodes = findChildrenInRange(doc, { from, to }, node => node.type.name === 'image') const images = findChildrenInRange(doc, { from, to }, node => node.type.name === 'image')
if (!nodes.length) { if (!images.length) {
return false return false
} }
return commands.forEach(nodes, ({ node, pos }, { index }) => { const tracker = new Tracker(tr)
const mappedPos = tr.steps
.slice(tr.steps.length - index) return commands.forEach(images, ({ node, pos }) => {
.reduce((newPos, step) => step.getMap().map(newPos), pos) const mapResult = tracker.map(pos)
if (mapResult.deleted) {
return false
}
const range = { const range = {
from: mappedPos, from: mapResult.position,
to: mappedPos + node.nodeSize, to: mapResult.position + node.nodeSize,
} }
return commands.insertContentAt(range, { return commands.insertContentAt(range, {
@@ -149,8 +154,36 @@ export const Figure = Node.create<FigureOptions>({
}) })
}, },
figureToImage: () => () => { figureToImage: () => ({ tr, commands }) => {
const { doc, selection } = tr
const { from, to } = selection
const figures = findChildrenInRange(doc, { from, to }, node => node.type.name === this.name)
if (!figures.length) {
return false return false
}
const tracker = new Tracker(tr)
return commands.forEach(figures, ({ node, pos }) => {
const mapResult = tracker.map(pos)
if (mapResult.deleted) {
return false
}
const range = {
from: mapResult.position,
to: mapResult.position + node.nodeSize,
}
return commands.insertContentAt(range, {
type: 'image',
attrs: {
src: node.attrs.src,
},
})
})
}, },
} }
}, },