import type { InsertResult } from '@admin/utils/editor/insert-result' import type { EditorView } from '@codemirror/view' export function transformSelectedMarkdownLines( view: EditorView | null, currentValue: string, transformLine: (line: string, index: number) => string, fallbackLine: string ): InsertResult { if (!view) { return { newValue: `${currentValue}${currentValue ? '\n' : ''}${fallbackLine}`, newCursorPos: currentValue.length + fallbackLine.length } } const { from, to } = view.state.selection.main const startLine = view.state.doc.lineAt(from) const endLine = view.state.doc.lineAt(to) const effectiveEndLine = to > from && to === endLine.from ? view.state.doc.lineAt(to - 1) : endLine const start = startLine.from const end = effectiveEndLine.to const selected = view.state.doc.sliceString(start, end) const selectedLines = selected.length > 0 ? selected.split('\n') : [''] const nextLines = selectedLines.map((line, index) => transformLine(line || fallbackLine, index)) const nextText = nextLines.join('\n') view.dispatch({ changes: { from: start, to: end, insert: nextText }, selection: { anchor: start + nextText.length } }) return { newValue: currentValue.slice(0, start) + nextText + currentValue.slice(end), newCursorPos: start + nextText.length } }