import type { TopLevelBlockDirection } from './top-level-block-direction' import type { Editor } from '@tiptap/react' import { TextSelection } from '@tiptap/pm/state' // Swaps the block that holds the cursor with its previous or next sibling at the top of the // document, keeping the cursor at the same offset inside the moved block. export function moveTopLevelBlock(editor: Editor, direction: TopLevelBlockDirection): boolean { const { state, view } = editor const { $from, from } = state.selection if ($from.depth < 1) return false const index = $from.index(0) const siblingIndex = direction === 'up' ? index - 1 : index + 1 if (siblingIndex < 0 || siblingIndex >= state.doc.childCount) return false const block = state.doc.child(index) const sibling = state.doc.child(siblingIndex) const blockStart = $from.before(1) const offsetInBlock = from - blockStart const insertAt = direction === 'up' ? blockStart - sibling.nodeSize : blockStart + sibling.nodeSize const tr = state.tr.delete(blockStart, blockStart + block.nodeSize).insert(insertAt, block) tr.setSelection(TextSelection.near(tr.doc.resolve(insertAt + offsetInBlock))) view.dispatch(tr.scrollIntoView()) return true }