import { EditorSelection, Transaction } from '@codemirror/state' import type { EditorView } from '@codemirror/view' import type { Editor } from '../plugin/editor' import { INLINE_SEMANTIC_CHANGE_ANNOTATION, INLINE_SEMANTIC_TEXT_CHANGE_ANNOTATION, inlineSemanticTextChangeFromChangeSpec, } from './inline-semantic-ops' import type { TextTransformResult } from './source-formatting' import type { TableCommandResult } from './commands/table-commands' export function dispatchTableResult(view: EditorView, result: TableCommandResult, scrollIntoView = true): boolean { if ((view as unknown as { destroyed: boolean }).destroyed || view.state.readOnly) return false view.dispatch({ changes: result.changes, selection: EditorSelection.create([result.selection]), annotations: Transaction.userEvent.of('input'), scrollIntoView, }) return true } export function dispatchTextTransform( view: EditorView, result: TextTransformResult, userEvent = 'input', ): void { if ((view as unknown as { destroyed: boolean }).destroyed || view.state.readOnly) return const semanticTextChange = result.semantic ? inlineSemanticTextChangeFromChangeSpec(result.changes) : undefined view.dispatch({ changes: result.changes, selection: EditorSelection.single(result.selectionStart, result.selectionEnd), scrollIntoView: true, annotations: result.semantic ? [ Transaction.userEvent.of(userEvent), INLINE_SEMANTIC_CHANGE_ANNOTATION.of(result.semantic), ...(semanticTextChange ? [INLINE_SEMANTIC_TEXT_CHANGE_ANNOTATION.of(semanticTextChange)] : []), ] : Transaction.userEvent.of(userEvent), }) } export function dispatchTransformResult( editor: Editor, result: TextTransformResult, userEvent = 'input', ): void { const view = (editor as { getView?: () => EditorView | null }).getView?.() if (view) { dispatchTextTransform(view, result, userEvent) return } const changes = result.changes if (Array.isArray(changes)) { console.error('dispatchTransformResult: multi-range ChangeSpec received in non-CM6 fallback; this path only supports single-range edits.') return } if ( !(typeof changes === 'object' && changes !== null && 'from' in changes && 'to' in changes && 'insert' in changes && typeof (changes as { insert: unknown }).insert === 'string') ) { console.error('dispatchTransformResult: unsupported ChangeSpec shape in non-CM6 fallback; expected {from, to, insert: string}.') return } const single = changes as { from: number; to: number; insert: string } editor.replaceRange(single.insert, editor.offsetToPos(single.from), editor.offsetToPos(single.to)) editor.setSelection(editor.offsetToPos(result.selectionStart), editor.offsetToPos(result.selectionEnd)) }