import { Decoration, DecorationSet, ViewPlugin, ViewUpdate, WidgetType, MatchDecorator, EditorView, } from '@codemirror/view'; /** * @description 插入tag */ const placeholderTagMatcher = new MatchDecorator({ regexp: /\[\[\{(.+?)\}\]\]/g, decoration: (match) => { return Decoration.replace({ widget: new PlaceholderTag(`{${match[1]}}`) }); }, }); // 定义一个 PlaceholderTag 类,继承自 WidgetType class PlaceholderTag extends WidgetType { // 定义一个字符串类型的 id 属性,默认值为空字符串 id: string = ''; parentId: string = ''; // 定义一个字符串类型的 text 属性,默认值为空字符串 text: string = ''; // 构造函数,接收一个字符串类型的 text 参数 constructor(text: string) { // 调用父类的构造函数 super(); // 被替换的数据处理 if (text) { const { parentId, fieldId: id, name } = JSON.parse(text); if (id && name) { this.text = name; this.parentId = parentId; this.id = id; } } } eq(other: PlaceholderTag) { return this.text == other.text; } // 此处是我们的渲染方法 toDOM() { let elt = document.createElement('span'); if (!this.text) return elt; elt.className = 'cm-tag'; elt.textContent = this.text; return elt; } ignoreEvent() { return true; } } // 导出一个名为placeholders的常量,它是一个ViewPlugin实例,通过fromClass方法创建 const placeholderTag = ViewPlugin.fromClass( // 定义一个匿名类,该类继承自ViewPlugin的基类 class { // 定义一个属性placeholders,用于存储装饰集 placeholders: DecorationSet; // 构造函数,接收一个EditorView实例作为参数 constructor(view: EditorView) { // 调用placeholderMatcher.createDeco方法,根据传入的view创建装饰集,并赋值给placeholders属性 this.placeholders = placeholderTagMatcher.createDeco(view); } // update方法,用于在视图更新时更新装饰集 update(update: ViewUpdate) { // 调用placeholderMatcher.updateDeco方法,根据传入的update和当前的placeholders更新装饰集,并重新赋值给placeholders属性 this.placeholders = placeholderTagMatcher.updateDeco(update, this.placeholders); } }, // 配置对象,用于定义插件的行为 { // decorations属性,返回当前实例的placeholders属性,用于提供装饰集 decorations: (v) => v.placeholders, // provide属性,返回一个函数,该函数返回一个EditorView.atomicRanges的提供者 provide: (plugin) => EditorView.atomicRanges.of((view) => { // 从view中获取当前插件的placeholders属性,如果不存在则返回Decoration.none return view.plugin(plugin)?.placeholders || Decoration.none; }), }, ); export default placeholderTag;