替换ckeditor内容并添加undo history entry

Replace ckeditor content and add undo history entry

我有一个需要实现的基本功能,但找不到有关如何实现的信息:我只是想用自定义标记替换 CKEditor 的所有内容并添加一个撤消历史记录条目,以便您可以返回到替换前的版本。

  1. 所以替换内容的基本命令是 editor.setData 但它不会添加撤消历史记录,将调用包装在 editor.model.change 中的条目也不会改变行为。
  2. 然后在文档的深处有关于如何添加(但不是替换)自定义 html 到正在添加撤消历史记录条目的编辑器的信息:

    this.editor.model.change((writer) => {
          const html = '<p>aaa</p><ul><li>huu</li><li>zzzz</li></ul><p>ssss</p>'
          const viewFragment = this.editor.data.processor.toView(html);
          const modelFragment = this.editor.data.toModel(viewFragment);
          this.editor.model.insertContent(modelFragment);
          this.editor.model.insertContent(modelFragment);
          this.editor.editing.view.scrollToTheSelection();
    });
    

那么我如何替换编辑器的内容添加一个撤消历史条目?我只能达到其中一个要求,不能同时达到两个要求。

这是一个 selects all the text first and then inserts 自定义文本的示例:

import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import Undo from '@ckeditor/ckeditor5-undo/src/undo';
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';

class Replace extends Plugin {
    init() {
        const editor = this.editor;

        editor.ui.componentFactory.add( 'Replace', locale => {
            const replaceButtonView = new ButtonView( locale );

            replaceButtonView.set( {
                label: 'Replace',
                withText: true,
            });

            replaceButtonView.on( 'execute', () => {
                editor.execute('selectAll');
                const html = '<p>aaa</p><ul><li>huu</li><li>zzzz</li></ul><p>ssss</p>';
                const viewFragment = editor.data.processor.toView(html);
                const modelFragment = editor.data.toModel(viewFragment);
                editor.model.insertContent(modelFragment);
                editor.editing.view.scrollToTheSelection();
            });

            return replaceButtonView;
        } );
    }
}

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ Essentials, Paragraph, Undo, Replace ],
        toolbar: [ 'undo', 'Replace' ]
    } )
    .then( editor => {
        console.log( 'Editor was initialized', editor );
    } )
    .catch( error => {
        console.error( error.stack );
    } );

直播: