Procházet zdrojové kódy

Other: Add unwrapElement method to UpcastWriter.

Mateusz Samsel před 6 roky
rodič
revize
1911d8d2ba

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

@@ -172,6 +172,27 @@ export default class UpcastWriter {
 		return false;
 	}
 
+	/**
+	 * Removes given element from view structure and places its children in its position.
+	 *
+	 * @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 );
+
+			return true;
+		}
+
+		return false;
+	}
+
 	/**
 	 * 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 elements', () => {
+			const documentFragment = dataprocessor.toView( '<ul><li><p>foo</p></li></ul>' );
+			const paragraph = documentFragment.getChild( 0 ).getChild( 0 ).getChild( 0 );
+			const unwrapStatus = writer.unwrapElement( paragraph );
+
+			expect( unwrapStatus ).to.be.true;
+			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 );
+			const unwrapStatus = writer.unwrapElement( span );
+
+			expect( unwrapStatus ).to.be.true;
+			expect( dataprocessor.toData( documentFragment ) ).to.equal(
+				'<p><strong>foo</strong><a href="example.com">example</a>bar</p>' );
+		} );
+
+		it( 'should not be applied to elements without parent', () => {
+			const element = new Element( 'p', null, 'foo' );
+			const unwrapStatus = writer.unwrapElement( element );
+
+			expect( unwrapStatus ).to.be.false;
+			expect( dataprocessor.toData( element ) ).to.equal( '<p>foo</p>' );
+		} );
+	} );
+
 	describe( 'rename', () => {
 		it( 'should rename simple element', () => {
 			const el = view.getChild( 0 ).getChild( 1 );