8
0
Просмотр исходного кода

Changed: `view.Element` constructor should stringify attributes.

Szymon Cofalik 8 лет назад
Родитель
Сommit
0726060227

+ 25 - 5
packages/ckeditor5-engine/src/view/element.js

@@ -60,11 +60,7 @@ export default class Element extends Node {
 		 * @protected
 		 * @protected
 		 * @member {Map} #_attrs
 		 * @member {Map} #_attrs
 		 */
 		 */
-		if ( isPlainObject( attrs ) ) {
-			this._attrs = objectToMap( attrs );
-		} else {
-			this._attrs = new Map( attrs );
-		}
+		this._attrs = parseAttributes( attrs );
 
 
 		/**
 		/**
 		 * Array of child nodes.
 		 * Array of child nodes.
@@ -723,6 +719,30 @@ export default class Element extends Node {
 	 */
 	 */
 }
 }
 
 
+// Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
+// as an object (instead of `Map`), the object is transformed to the map. Attributes with `null` value are removed.
+// Attributes with non-`String` value are converted to `String`.
+//
+// @param {Object|Map} attrs Attributes to parse.
+// @returns {Map} Parsed attributes.
+function parseAttributes( attrs ) {
+	if ( isPlainObject( attrs ) ) {
+		attrs = objectToMap( attrs );
+	} else {
+		attrs = new Map( attrs );
+	}
+
+	for ( const [ key, value ] of attrs ) {
+		if ( value === null ) {
+			attrs.delete( key );
+		} else if ( typeof value != 'string' ) {
+			attrs.set( key, String( value ) );
+		}
+	}
+
+	return attrs;
+}
+
 // Parses inline styles and puts property - value pairs into styles map.
 // Parses inline styles and puts property - value pairs into styles map.
 // Styles map is cleared before insertion.
 // Styles map is cleared before insertion.
 //
 //

+ 8 - 0
packages/ckeditor5-engine/tests/view/element.js

@@ -41,6 +41,14 @@ describe( 'Element', () => {
 			expect( el.getAttribute( 'foo' ) ).to.equal( 'bar' );
 			expect( el.getAttribute( 'foo' ) ).to.equal( 'bar' );
 		} );
 		} );
 
 
+		it( 'should stringify attributes', () => {
+			const el = new Element( 'p', { foo: true, bar: null, object: {} } );
+
+			expect( el.getAttribute( 'foo' ) ).to.equal( 'true' );
+			expect( el.getAttribute( 'bar' ) ).to.be.undefined;
+			expect( el.getAttribute( 'object' ) ).to.equal( '[object Object]' );
+		} );
+
 		it( 'should create element with children', () => {
 		it( 'should create element with children', () => {
 			const child = new Element( 'p', { foo: 'bar' } );
 			const child = new Element( 'p', { foo: 'bar' } );
 			const parent = new Element( 'div', [], [ child ] );
 			const parent = new Element( 'div', [], [ child ] );