清除codemirror6的输入历史
创建一个基础的编辑器
这个示例中主动向编辑器添加了历史记录的功能。
js
import { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { history } from '@codemirror/commands';
const state = EditorState.create({
doc: '',
extensions: [history()]
});
const view = new EditorView({
parent: document.querySelector('#app'),
state,
});
提示
这样实际上快捷键undo
是没有的,非常基础的扩展。
动态修改配置
借助Compartments
,可以动态的为编辑器配置扩展,调整代码:
js
import { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { history } from '@codemirror/commands';
const historyComp = new Compartment();
const state = EditorState.create({
doc: '',
extensions: [historyComp.of(history())]
});
const view = new EditorView({
parent: document.querySelector('#app'),
state,
});
const clearHistory = () => {
// 移除历史扩展
view.dispatch({
effects: historyComp.reconfigure([])
});
// 重新添加历史扩展
view.dispatch({
effects: historyComp.reconfigure(history())
});
}
冲突的问题
codemirror
提供了两个扩展配置项
minimalSetup
:迷你的扩展包
注释:
A minimal set of extensions to create a functional editor. Only
includes the default keymap, undo
history, special character
highlighting, custom selection
drawing, and default highlight
style.
basicSetup
:基础扩展包
注释:
This is an extension value that just pulls together a number of
extensions that you might want in a basic editor. It is meant as a
convenient helper to quickly set up CodeMirror without installing
and importing a lot of separate packages.
Specifically, it includes...
- the default command bindings
- line numbers
- special character highlighting
- the undo history
- a fold gutter
- custom selection drawing
- drop cursor
- multiple selections
- reindentation on input
- the default highlight style (as fallback)
- bracket matching
- bracket closing
- autocompletion
- rectangular selection and crosshair cursor
- active line highlighting
- active line gutter highlighting
- selection match highlighting
- search
- linting
(You'll probably want to add some language package to your setup
too.)
This extension does not allow customization. The idea is that,
once you decide you want to configure your editor more precisely,
you take this package's source (which is just a bunch of imports
and an array literal), copy it into your own code, and adjust it
as desired.
当你使用的这两扩展包之一时,因为其内置了历史扩展,会导致我们使用当前添加的Compartments
来reconfigure
时无效。
目前作者的解决方案是将扩展包中的部分扩展手动添加到extensions
中,比如基础快捷键、历史快捷键等。