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 setMarkdownLinkAtCursor( view: EditorView | null, currentValue: string, url: string ): InsertResult { const href = url.trim() if (!href) { return { newValue: currentValue, newCursorPos: currentValue.length } } if (!view) { const linkText = href const markdownLink = `[${linkText}](${href})` return { newValue: currentValue + markdownLink, newCursorPos: currentValue.length + 1 + linkText.length } } const markdown = view.state.doc.toString() const { from, to } = view.state.selection.main const selected = view.state.sliceDoc(from, to) const existingLink = findMarkdownLinkRange(markdown, from, to) const linkText = existingLink?.text || selected || href const markdownLink = `[${linkText}](${href})` const replaceFrom = existingLink?.start ?? from const replaceTo = existingLink?.end ?? to const nextCursorPos = replaceFrom + 1 + linkText.length view.dispatch({ changes: { from: replaceFrom, to: replaceTo, insert: markdownLink }, selection: { anchor: replaceFrom + 1, head: nextCursorPos } }) return { newValue: markdown.slice(0, replaceFrom) + markdownLink + markdown.slice(replaceTo), newCursorPos: nextCursorPos } }