Преглед изворни кода

Added `normalizeHtml` function and tests.

Maksymilian Barnaś пре 9 година
родитељ
комит
e2faec9cd8

+ 20 - 0
packages/ckeditor5-utils/src/normalizehtml.js

@@ -0,0 +1,20 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+import HtmlDataProcessor from '/ckeditor5/engine/dataprocessor/htmldataprocessor.js';
+import { stringify } from '/tests/engine/_utils/view.js';
+
+/**
+ * Parses given string of HTML and returns normalized HTML.
+ *
+ * @param {String} html HTML string to normalize.
+ * @returns {String} Normalized HTML string.
+ */
+export default function normalizeHtml( html ) {
+	const processor = new HtmlDataProcessor();
+	const parsed = processor.toView( html );
+
+	return stringify( parsed );
+}

+ 59 - 0
packages/ckeditor5-utils/tests/normalizehtml.js

@@ -0,0 +1,59 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+import normalizeHtml from '/ckeditor5/utils/normalizehtml.js';
+
+describe( 'utils', () => {
+	describe( 'normalizeHtml', () => {
+		it( 'should sort attributes', () => {
+			let actual = '<a style="border:1px;" class="" href="file://"></a>';
+			let expected = '<a class="" href="file://" style="border:1px;"></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should normalize styles', () => {
+			let actual = '<a style="border:1px"></a>';
+			let expected = '<a style="border:1px;"></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should lowercase attributes', () => {
+			let actual = '<A CLASS="" HREF="file://" STYLE="border:1px;"></A>';
+			let expected = '<a class="" href="file://" style="border:1px;"></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should trim whitespace', () => {
+			let actual = '<a class="  " href="file://"      style="border:  1px"></a>';
+			let expected = '<a class="" href="file://" style="border:1px;"></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should remove empty style attribute', () => {
+			let actual = '<a style=""></a>';
+			let expected = '<a></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should leave empty class attribute', () => {
+			let actual = '<p class=""></p>';
+			let expected = '<p class=""></p>';
+
+			expect( normalizeHtml( actual ) ).to.be.equal( expected );
+		} );
+
+		it( 'should not sort attribute value', () => {
+			let actual = '<a class="a b"></a>';
+			let expected = '<a class="b a"></a>';
+
+			expect( normalizeHtml( actual ) ).to.be.not.equal( expected );
+		} );
+	} );
+} );