替换ckeditor内容并添加撤消历史条目

Tob*_* P. 5 javascript ckeditor ckeditor5

我有一个需要实现的基本功能,但找不到有关如何执行此操作的信息:我只想用自定义标记替换 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();
    });
    
    Run Code Online (Sandbox Code Playgroud)

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

Aze*_*eem 3

下面是一个首先选择所有文本然后插入自定义文本的示例:

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 );
    } );
Run Code Online (Sandbox Code Playgroud)

居住:

CKEditor5-替换-撤消-演示

  • 完美的!“selectAll”技巧没有任何记录,但这正是我想要的。 (2认同)