From eac291572d40c1f4af3e8aab4317034359a4f3b3 Mon Sep 17 00:00:00 2001 From: Ryan J Daw Date: Mon, 14 Jan 2013 11:55:59 -0800 Subject: [PATCH] Fixes issues with charset moving - Charset would not be moved correctly with keepBreaks - Performance improvement due to previous method accumulating a large buffer in a RegExpi, which is really slow, especially when it would not actually find a charset declaration. --- lib/clean.js | 22 +++++++++++++++------- test/unit-test.js | 8 ++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/lib/clean.js b/lib/clean.js index 3abec66d..cd1a531d 100644 --- a/lib/clean.js +++ b/lib/clean.js @@ -251,18 +251,26 @@ var CleanCSS = { // restore rect(...) zeros syntax for 4 zeros replace(/rect\(\s?0(\s|,)0[ ,]0[ ,]0\s?\)/g, 'rect(0$10$10$10)'); + + // move first charset to the beginning + replace(function moveCharset() { + // get first charset in stylesheet + var match = data.match(/@charset [^;]+;/); + var firstCharset = match ? match[0] : ''; + + // remove all charsets + data = data.replace(/@charset [^;]+;\n?/g, ''); + + // reattach first charset + if (firstCharset !== '') { + data = firstCharset + (options.keepBreaks ? '\n': '') + data; + } + }); // empty elements if (options.removeEmpty) replace(/[^\}]+?\{\}/g, ''); - // move first charset to the beginning - if (data.indexOf('charset') > 0) - replace(/(.+)(@charset [^;]+;)/, '$2$1'); - - // remove all extra charsets that are not at the beginning - replace(/(.)(?:@charset [^;]+;)/g, '$1'); - // remove universal selector when not needed (*#id, *.class etc) replace(/\*([\.#:\[])/g, '$1'); diff --git a/test/unit-test.js b/test/unit-test.js index 4f9080b4..2499943e 100644 --- a/test/unit-test.js +++ b/test/unit-test.js @@ -133,6 +133,14 @@ vows.describe('clean-units').addBatch({ 'line breaks with whitespace lines': [ 'div \n \t\n \na\r\n, p { width:500px }', 'div' + lineBreak + 'a' + lineBreak + ',p{width:500px}' + ], + 'charset not at beginning': [ + "a{ color: #f10; }\n@charset 'utf-8';\nb { font-weight: bolder}", + "@charset 'utf-8';\na{color:#f10}\nb{font-weight:bolder}" + ], + 'charset multiple charsets': [ + "@charset 'utf-8';\ndiv :before { display: block }\n@charset 'utf-8';\na { color: #f10 }", + "@charset 'utf-8';\ndiv :before{display:block}\na{color:#f10}" ] }, { keepBreaks: true }), 'selectors': cssContext({ -- 2.34.1