diff --git a/src/imagecaption/imagecaptionengine.js b/src/imagecaption/imagecaptionengine.js index 3e104339..0ec52e3a 100644 --- a/src/imagecaption/imagecaptionengine.js +++ b/src/imagecaption/imagecaptionengine.js @@ -170,7 +170,11 @@ function insertMissingModelCaptionElement( evt, changeType, data, batch ) { if ( value.type == 'elementStart' && isImage( item ) && !getCaptionFromImage( item ) ) { batch.document.enqueueChanges( () => { - batch.insert( ModelPosition.createAt( item, 'end' ), new ModelElement( 'caption' ) ); + // Make sure that the image does not have caption already. + // https://github.com/ckeditor/ckeditor5-image/issues/78 + if ( !getCaptionFromImage( item ) ) { + batch.insert( ModelPosition.createAt( item, 'end' ), new ModelElement( 'caption' ) ); + } } ); } } diff --git a/tests/imagecaption/imagecaptionengine.js b/tests/imagecaption/imagecaptionengine.js index f6e430bc..f32ad9a4 100644 --- a/tests/imagecaption/imagecaptionengine.js +++ b/tests/imagecaption/imagecaptionengine.js @@ -252,6 +252,32 @@ describe( 'ImageCaptionEngine', () => { ); } ); + it( 'should not add caption element twice', () => { + const image = new ModelElement( 'image', { src: '', alt: '' } ); + const caption = new ModelElement( 'caption' ); + const batch = document.batch(); + + document.enqueueChanges( () => { + batch + // Since we are adding an empty image, this should trigger caption fixer. + .insert( ModelPosition.createAt( document.getRoot() ), image ) + // Add caption just after the image is inserted, in same batch and enqueue changes block. + .insert( ModelPosition.createAt( image ), caption ); + } ); + + // Check whether caption fixer added redundant caption. + expect( getModelData( document ) ).to.equal( + '[]' + ); + + expect( getViewData( viewDocument ) ).to.equal( + '[]
' + + '' + + '
' + + '
' + ); + } ); + it( 'should do nothing for other changes than insert', () => { setModelData( document, 'foo bar' ); const image = document.getRoot().getChild( 0 );