Fixes issues with charset moving
authorRyan J Daw <ryan@mobify.me>
Mon, 14 Jan 2013 19:55:59 +0000 (11:55 -0800)
committerRyan J Daw <ryan@mobify.me>
Mon, 14 Jan 2013 19:56:40 +0000 (11:56 -0800)
 - 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
test/unit-test.js

index 3abec66..cd1a531 100644 (file)
@@ -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');
 
index 4f9080b..2499943 100644 (file)
@@ -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({