清除codemirror6的输入历史

607#dc85a3b8

来自一个组件的[需求](https://github.com/imzbf/md-editor-v3/issues/427),6改造较大,不能直接像5那样直接调用`clearHistory`来清空。

创建一个基础的编辑器

这个示例中主动向编辑器添加了历史记录的功能。

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提供了两个扩展配置项

  1. 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
.

  1. 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...

(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.

当你使用的这两扩展包之一时,因为其内置了历史扩展,会导致我们使用当前添加的Compartmentsreconfigure时无效。

目前作者的解决方案是将扩展包中的部分扩展手动添加到extensions中,比如基础快捷键、历史快捷键等。

参与本文讨论

请先登录 GitHub 后留言

0/500

本文留言

0

这篇文章还没有留言,来写第一条吧。

1 / 1