import type { InsertResult } from '@admin/utils/editor/insert-result' import type { EditorView } from '@codemirror/view' import { findHighlightSpanRange } from '@admin/utils/editor/find-highlight-span-range' import { HIGHLIGHT_SPAN_PATTERN } from '@admin/utils/editor/highlight-span-pattern' export function removeHighlightSpanAtCursor( 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 selected = markdown.slice(from, to) HIGHLIGHT_SPAN_PATTERN.lastIndex = 0 const unwrappedSelected = selected.replace(HIGHLIGHT_SPAN_PATTERN, '$1') if (selected && selected !== unwrappedSelected) { view.dispatch({ changes: { from, to, insert: unwrappedSelected }, selection: { anchor: from + unwrappedSelected.length } }) return { newValue: markdown.slice(0, from) + unwrappedSelected + markdown.slice(to), newCursorPos: from + unwrappedSelected.length } } const highlightRange = findHighlightSpanRange(markdown, from, to) if (!highlightRange) { return { newValue: markdown, newCursorPos: to } } view.dispatch({ changes: { from: highlightRange.start, to: highlightRange.end, insert: highlightRange.text }, selection: { anchor: highlightRange.start + highlightRange.text.length } }) return { newValue: markdown.slice(0, highlightRange.start) + highlightRange.text + markdown.slice(highlightRange.end), newCursorPos: highlightRange.start + highlightRange.text.length } }