Skip to content

Commit

Permalink
Merge pull request #13851 from ckeditor/cf/4983
Browse files Browse the repository at this point in the history
Other: `MultiRootEditor` will first fire all `detachRoot` events and then all `addRoot` events if there are detached and added roots in the same batch.
  • Loading branch information
scofalik authored Apr 11, 2023
2 parents 64a99f1 + 40cb717 commit 629f8ab
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/ckeditor5-editor-multi-root/src/multirooteditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,13 +175,22 @@ export default class MultiRootEditor extends DataApiMixin( Editor ) {
this.model.document.on( 'change:data', () => {
const changedRoots = this.model.document.differ.getChangedRoots();

// Fire detaches first. If there are multiple roots removed and added in one batch, it should be easier to handle if
// changes aren't mixed. Detaching will usually lead to just removing DOM elements. Detaching first will lead to a clean DOM
// when new editables are added in `addRoot` event.
for ( const changes of changedRoots ) {
const root = this.model.document.getRoot( changes.name )!;

if ( changes.state == 'detached' ) {
this.fire<DetachRootEvent>( 'detachRoot', root );
}
}

for ( const changes of changedRoots ) {
const root = this.model.document.getRoot( changes.name )!;

if ( changes.state == 'attached' ) {
this.fire<AddRootEvent>( 'addRoot', root );
} else if ( changes.state == 'detached' ) {
this.fire<DetachRootEvent>( 'detachRoot', root );
}
}
} );
Expand Down
23 changes: 23 additions & 0 deletions packages/ckeditor5-editor-multi-root/tests/multirooteditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,29 @@ describe( 'MultiRootEditor', () => {
} );
} );

it( 'should first fire `detachRoot` event then `addRoot` event', () => {
const events = [];

return MultiRootEditor.create( { foo: '' }, { plugins: [ Paragraph, Undo ] } ).then( editor => {
editor.on( 'addRoot', () => {
events.push( 'addRoot' );
} );

editor.on( 'detachRoot', () => {
events.push( 'detachRoot' );
} );

editor.model.change( writer => {
writer.addRoot( 'bar' );
writer.detachRoot( 'foo' );
} );

return editor.destroy();
} ).then( () => {
expect( events ).to.deep.equal( [ 'detachRoot', 'addRoot' ] );
} );
} );

describe( 'EditorConfig#rootsAttributes', () => {
it( 'should load attributes from editor configuration', async () => {
editor = await MultiRootEditor.create( { foo: '', bar: '' }, {
Expand Down

0 comments on commit 629f8ab

Please sign in to comment.