问题
I have a basic functionality I need to implement and can't find the information on how to do it: I simply want to replace all of CKEditor's content with custom markup and add an undo history entry so you can go back to the version before replacing.
- So the basic command for replacing the content is
editor.setData
but it won't add an undo history, entry wrapping the call ineditor.model.change
won't change the behavior too. Then there is somewhere deep in the documentationthe information on how to add (but not replace) custom html to the editor which is adding an undo history entry:
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(); });
So how do I replace the content of the editor and add an undo history entry? I can only achieve one of the requirements but not both.
回答1:
Here's an example that selects all the text first and then inserts custom text:
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 );
} );
Live:
来源:https://stackoverflow.com/questions/61728192/replace-ckeditor-content-and-add-undo-history-entry