File
Blob: src/client/components/editor/lib/moved-textblock-selection.ts
| 1 | import { NodeSelection, TextSelection, type Selection } from "@tiptap/pm/state"; |
| 2 | import type { EditorView } from "@tiptap/pm/view"; |
| 3 | |
| 4 | function scheduleFrame(callback: FrameRequestCallback): number { |
| 5 | if (typeof requestAnimationFrame === "function") { |
| 6 | return requestAnimationFrame(callback); |
| 7 | } |
| 8 | |
| 9 | queueMicrotask(() => callback(0)); |
| 10 | return 0; |
| 11 | } |
| 12 | |
| 13 | export function getMovedTextblockCursorPos(selection: Selection): number | null { |
| 14 | if (!(selection instanceof NodeSelection) || !selection.node.isTextblock) { |
| 15 | return null; |
| 16 | } |
| 17 | |
| 18 | return Math.max(selection.from + 1, selection.to - 1); |
| 19 | } |
| 20 | |
| 21 | function finalizeMovedTextblockSelection(view: EditorView): boolean { |
| 22 | view.updateState(view.state); |
| 23 | |
| 24 | const cursorPos = getMovedTextblockCursorPos(view.state.selection); |
| 25 | if (cursorPos === null) return false; |
| 26 | |
| 27 | view.dispatch( |
| 28 | view.state.tr.setSelection(TextSelection.create(view.state.doc, cursorPos)).setMeta("addToHistory", false), |
| 29 | ); |
| 30 | return true; |
| 31 | } |
| 32 | |
| 33 | export function scheduleMovedTextblockSelectionFinalization(view: EditorView) { |
| 34 | scheduleFrame(() => { |
| 35 | if (view.isDestroyed) return; |
| 36 | finalizeMovedTextblockSelection(view); |
| 37 | }); |
| 38 | } |