2 normal kinds of codemirror event listener: doc change, selection change
- onDocChange: triggered when doc changes
- onSelectionChange: triggered when selection changes
npm install @tidbcloud/codemirror-extension-events
You need to install its peer dependencies as well:
npm install @codemirror/view @codemirror/state
import { EditorView } from '@codemirror/view'
import { EditorState } from '@codemirror/state'
import {
onDocChange,
onSelectionChange,
SelectionRange
} from '@tidbcloud/codemirror-extension-events'
const docChangeHandler = (view: EditorView, state: EditorState, doc: string) => {
console.log(doc)
}
const selectionChangeHandler = (view: EditorView, state: EditorState, ranges: SelectionRange[]) => {
console.log(ranges)
}
const editorView = new EditorView({
state: EditorState.create({
doc,
extensions: [
onDocChange(docChangeHandler),
onSelectionChange(selectionChangeHandler)
]
})
})
type DocChangeHandler = (view: EditorView, state: EditorState, content: string) => void
function onDocChange(handler: DocChangeHandler): Extension
type SelectionRange = {
from: number
to: number
}
type SelectionChangeHandler = (
view: EditorView,
state: EditorState,
selRanges: SelectionRange[]
) => void
function onSelectionChange(handler: SelectionChangeHandler): Extension