import type { Editor } from '@tiptap/react' import { TextSelection } from '@tiptap/pm/state' // Moves the top-level block at `fromIndex` so it ends up at `toIndex` in the document, keeping the // cursor at the same offset inside the moved block. export function moveTopLevelBlockTo(editor: Editor, fromIndex: number, toIndex: number): boolean { const { state, view } = editor const { doc, selection } = state if (fromIndex === toIndex || fromIndex < 0 || fromIndex >= doc.childCount) return false let blockStart = 0 for (let index = 0; index < fromIndex; index++) blockStart += doc.child(index).nodeSize const block = doc.child(fromIndex) const cursorOffset = Math.min(Math.max(selection.from - blockStart, 1), block.nodeSize - 1) const tr = state.tr.delete(blockStart, blockStart + block.nodeSize) let insertAt = 0 for (let index = 0; index < Math.min(toIndex, tr.doc.childCount); index++) { insertAt += tr.doc.child(index).nodeSize } tr.insert(insertAt, block) tr.setSelection(TextSelection.near(tr.doc.resolve(insertAt + cursorOffset))) view.dispatch(tr.scrollIntoView()) return true }