Permalink
Browse files

add url() mapping plugin

  • Loading branch information...
1 parent 764f18b commit 5157fb809eaa45b56e1030cb1da0ae1c76a0828a @tj tj committed Sep 17, 2012
Showing with 88 additions and 0 deletions.
  1. +60 −0 lib/plugins/url.js
  2. +1 −0 lib/rework.js
  3. +7 −0 test/fixtures/url.css
  4. +7 −0 test/fixtures/url.out.css
  5. +13 −0 test/rework.js
View
@@ -0,0 +1,60 @@
+
+/**
+ * Module dependencies.
+ */
+
+var utils = require('../utils');
+
+/**
+ * Map `url()` calls.
+ *
+ * body {
+ * background: url(/images/bg.png);
+ * }
+ *
+ * yields:
+ *
+ * body {
+ * background: url(http://example.com/images/bg.png);
+ * }
+ *
+ */
+
+module.exports = function(fn) {
+ return function(style, rework){
+ style.rules.forEach(function(rule){
+ if (rule.keyframes) return keyframes(fn);
+ if (rule.declarations) url(rule, fn);
+ });
+ }
+};
+
+/**
+ * Map within keyframes.
+ *
+ * @api private
+ */
+
+function keyframes(fn) {
+ rule.keyframes.forEach(function(keyframe){
+ if (!rule.vendor) return;
+ url(keyframe, fn);
+ });
+}
+
+/**
+ * Map url().
+ *
+ * @api private
+ */
+
+function url(rule, fn) {
+ rule.declarations = rule.declarations.map(function(decl, i){
+ if (!~decl.value.indexOf('url(')) return decl;
+ decl.value = decl.value.replace(/url\(([^)]+)\)/, function(_, url){
+ url = utils.stripQuotes(url);
+ return 'url("' + fn(url) + '")';
+ });
+ return decl;
+ });
+}
View
@@ -83,3 +83,4 @@ exports.prefixSelectors = require('./plugins/prefix-selectors');
exports.keyframes = require('./plugins/keyframes');
exports.opacity = require('./plugins/opacity');
exports.at2x = require('./plugins/at2x');
+exports.url = require('./plugins/url');
View
@@ -0,0 +1,7 @@
+body {
+ background: url('/images/bg.png') repeat-x;
+}
+
+#logo {
+ background: url(/images/logo.jpeg);
+}
@@ -0,0 +1,7 @@
+body {
+ background: url("http://example.com/images/bg.png") repeat-x
+}
+
+#logo {
+ background: url("http://example.com/images/logo.jpeg")
+}
View
@@ -84,4 +84,17 @@ describe('rework', function(){
.should.equal(fixture('keyframes.out'));
})
})
+
+ describe('.url(fn)', function(){
+ it('should map urls', function(){
+ function rewrite(url) {
+ return 'http://example.com' + url;
+ }
+
+ rework(fixture('url'))
+ .use(rework.url(rewrite))
+ .toString()
+ .should.equal(fixture('url.out'));
+ })
+ })
})

0 comments on commit 5157fb8

Please sign in to comment.