Fixes #450 - color names to hex codes.
authorJakub Pawlowicz <contact@jakubpawlowicz.com>
Fri, 30 Jan 2015 22:32:25 +0000 (22:32 +0000)
committerJakub Pawlowicz <contact@jakubpawlowicz.com>
Sat, 31 Jan 2015 10:25:26 +0000 (10:25 +0000)
Regexp matching color names was too greedy and was matching some
other values as well.

On the downside we need to run the replacement twice.

On the upside it extracts replacement functions so we get a slight
speed boost.

History.md
lib/colors/hex-name-shortener.js
test/selectors/optimizers/simple-test.js

index 6fac3ec..8e52884 100644 (file)
 * Fixed issue [#442](https://github.com/GoalSmashers/clean-css/issues/442) - space before adjacent `nav`.
 * Fixed issue [#445](https://github.com/GoalSmashers/clean-css/issues/445) - regression issue in url processor.
 
+[3.0.8 / 2015-xx-xx](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.7...v3.0.8)
+==================
+
+* Fixed issue [#450](https://github.com/GoalSmashers/clean-css/issues/450) - name to hex color converting.
+
 [3.0.7 / 2015-01-22](https://github.com/jakubpawlowicz/clean-css/compare/v3.0.6...v3.0.7)
 ==================
 
index c0862d0..2af2f4e 100644 (file)
@@ -162,22 +162,25 @@ for (var name in COLORS) {
     toHex[name] = hex;
 }
 
-var toHexPattern = new RegExp('(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig');
+var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig');
 var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig');
 
+function hexConverter(match, prefix, colorValue, suffix) {
+  return prefix + toHex[colorValue.toLowerCase()] + suffix;
+}
+
+function nameConverter(match, colorValue, suffix) {
+  return toName[colorValue.toLowerCase()] + suffix;
+}
+
 HexNameShortener.shorten = function (value) {
   var hasHex = value.indexOf('#') > -1;
-  var shortened = value.replace(toHexPattern, function(match, colorValue, suffix) {
-    return toHex[colorValue.toLowerCase()] + suffix;
-  });
+  var shortened = value.replace(toHexPattern, hexConverter);
 
-  if (hasHex) {
-    shortened = shortened.replace(toNamePattern, function(match, colorValue, suffix) {
-      return toName[colorValue.toLowerCase()] + suffix;
-    });
-  }
+  if (shortened != value)
+    shortened = shortened.replace(toHexPattern, hexConverter);
 
-  return shortened;
+  return hasHex ? shortened.replace(toNamePattern, nameConverter) : shortened;
 };
 
 module.exports = HexNameShortener;
index da90646..813de29 100644 (file)
@@ -220,6 +220,10 @@ vows.describe(SimpleOptimizer)
       'partial name further down to hex': [
         'a{background:url(test.png) blueish}',
         ['background:url(test.png) blueish']
+      ],
+      'partial name as a suffix': [
+        'a{font-family:alrightsanslp-black}',
+        ['font-family:alrightsanslp-black']
       ]
     })
   )