import type { InsertResult } from '@admin/utils/editor/insert-result' import type { EditorView } from '@codemirror/view' export function insertTextAtCursor( view: EditorView | null, currentValue: string, opts: { before: string; after: string; placeholder: string } ): InsertResult { const { before, after, placeholder } = opts if (view) { const { from, to } = view.state.selection.main const selected = view.state.sliceDoc(from, to) const insert = selected || placeholder const newText = `${before}${insert}${after}` view.dispatch({ changes: { from, to, insert: newText }, selection: { anchor: from + before.length, head: from + before.length + insert.length } }) return { newValue: currentValue.slice(0, from) + newText + currentValue.slice(to), newCursorPos: from + before.length + insert.length } } const insert = placeholder const newText = `${before}${insert}${after}` return { newValue: currentValue + newText, newCursorPos: currentValue.length + before.length + insert.length } }