interface HistoryConfig {
/**
The minimum depth (amount of events) to store. Defaults to 100.
*/
minDepth?: number;
/**
The maximum time (in milliseconds) that adjacent events can be
apart and still be grouped together. Defaults to 500.
*/
newGroupDelay?: number;
}
/**
Create a history extension with the given configuration.
*/
declare function history(config?: HistoryConfig): Extension;
import { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { history } from '@codemirror/commands';
const state = EditorState.create({
doc: 'my source code',
extensions: [history({ minDepth: 10 })],
});
const view = new EditorView({
parent: document.querySelector('#editor'),
state,
});
撤消/重做功能是通过
Extension
实现的。可以“在运行时”添加或删除扩展,即在 EditorView
的生命周期内,使用 Compartment
。据我了解,隔间是占位符或盒子,允许您在创建编辑器后放置或删除扩展。
使用这些隔间,我们可以添加和删除 history()
扩展:
import { history, historyKeymap } from '@codemirror/commands';
let undoRedo = new Compartment;
let editor = new EditorView({
state: EditorState.create({
extensions: [
basicSetup,
//...
undoRedo.of([history()]),
keymap.of([
...historyKeymap,
])
]
}),
parent: document.getElementById("txtInput")
});
function resetUndoRedo() {
editor.dispatch({
effects: undoRedo.reconfigure([]) //first remove history() to clear it!!
});
editor.dispatch({
effects: undoRedo.reconfigure([history()])
});
}
//a typical usage:
function setEditorText(text) {
let transaction = editor.state.update({ changes: {
from: 0,
to: editor.state.doc.length,
insert: text}
});
editor.update([transaction]);
resetUndoRedo();
}