import type { InsertResult } from '@admin/utils/editor/insert-result' import type { EditorView } from '@codemirror/view' import { findMarkdownLinkRange } from '@admin/utils/editor/find-markdown-link-range' export function removeMarkdownLinkAtCursor( view: EditorView | null, currentValue: string ): InsertResult { if (!view) { return { newValue: currentValue, newCursorPos: currentValue.length } } const markdown = view.state.doc.toString() const { from, to } = view.state.selection.main const existingLink = findMarkdownLinkRange(markdown, from, to) if (!existingLink) { return { newValue: markdown, newCursorPos: to } } const nextCursorPos = existingLink.start + existingLink.text.length view.dispatch({ changes: { from: existingLink.start, to: existingLink.end, insert: existingLink.text }, selection: { anchor: nextCursorPos } }) return { newValue: markdown.slice(0, existingLink.start) + existingLink.text + markdown.slice(existingLink.end), newCursorPos: nextCursorPos } }