Browse Source

Merge pull request #1772 from ckeditor/t/paste-from-office/69

Other: Add unwrapElement() method to UpcastWriter.
Maciej 6 years ago
parent
commit
42ad00c36c

+ 18 - 0
packages/ckeditor5-engine/src/view/upcastwriter.js

@@ -173,6 +173,24 @@ export default class UpcastWriter {
 	}
 
 	/**
+	 * Removes given element from view structure and places its children in its position.
+	 * It does nothing if element has no parent.
+	 *
+	 * @param {module:engine/view/element~Element} element Element which will be unwrapped
+	 * @returns {Booolean} Whether element was successfully unwrapped.
+	 */
+	unwrapElement( element ) {
+		const parent = element.parent;
+
+		if ( parent ) {
+			const index = parent.getChildIndex( element );
+
+			this.remove( element );
+			this.insertChild( index, element.getChildren(), parent );
+		}
+	}
+
+	/**
 	 * Renames element by creating a copy of a given element but with its name changed and then moving contents of the
 	 * old element to the new one.
 	 *

+ 30 - 0
packages/ckeditor5-engine/tests/view/upcastwriter.js

@@ -328,6 +328,36 @@ describe( 'UpcastWriter', () => {
 		} );
 	} );
 
+	describe( 'unwrapElement', () => {
+		it( 'should unwrap simple element', () => {
+			const documentFragment = dataprocessor.toView( '<ul><li><p>foo</p></li></ul>' );
+			const paragraph = documentFragment.getChild( 0 ).getChild( 0 ).getChild( 0 );
+
+			writer.unwrapElement( paragraph );
+
+			expect( dataprocessor.toData( documentFragment ) ).to.equal( '<ul><li>foo</li></ul>' );
+		} );
+
+		it( 'should unwrap element with children', () => {
+			const documentFragment = dataprocessor.toView(
+				'<p><span style="color:red"><strong>foo</strong><a href="example.com">example</a>bar</span></p>' );
+			const span = documentFragment.getChild( 0 ).getChild( 0 );
+
+			writer.unwrapElement( span );
+
+			expect( dataprocessor.toData( documentFragment ) ).to.equal(
+				'<p><strong>foo</strong><a href="example.com">example</a>bar</p>' );
+		} );
+
+		it( 'should do nothing for elements without parent', () => {
+			const element = new Element( 'p', null, 'foo' );
+
+			writer.unwrapElement( element );
+
+			expect( dataprocessor.toData( element ) ).to.equal( '<p>foo</p>' );
+		} );
+	} );
+
 	describe( 'rename', () => {
 		it( 'should rename simple element', () => {
 			const el = view.getChild( 0 ).getChild( 1 );