guess the mimetype, and properly encode non-base64 uris

This commit is contained in:
Jay Adkisson
2012-12-28 13:19:55 -08:00
committed by Luke Page
parent 5b241fd3a7
commit 2394c0065e
5 changed files with 43 additions and 10 deletions

View File

@@ -351,18 +351,34 @@ tree.functions = {
throw new Error('data-uri() is not supported in the browser.');
}
var fs = require('fs');
var data = fs.readFileSync(path.value);
mimetype = mimetype.value;
path = (path && path.value);
if (/;base64$/.test(mimetype)) {
data = (new Buffer(data)).toString('base64');
var fs = require('fs');
var useBase64 = false;
// detect the mimetype if not given
if (arguments.length < 2) {
var mime = require('mime');
path = mimetype;
mimetype = mime.lookup(path);
// use base 64 unless it's an ASCII or UTF-8 format
var charset = mime.charsets.lookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
if (useBase64) mimetype += ';base64';
}
else {
useBase64 = /;base64$/.test(mimetype)
}
var contents = new(tree.Anonymous)('data:'+mimetype+','+data);
var buf = fs.readFileSync(path);
return new(tree.URL)(contents);
buf = useBase64 ? buf.toString('base64')
: encodeURIComponent(buf);
var uri = "'data:"+mimetype+','+buf+"'";
return new(tree.URL)(new(tree.Anonymous)(uri));
}
};

View File

@@ -10,7 +10,7 @@
"main" : "./lib/less/index",
"directories" : { "test": "./test" },
"engines" : { "node": ">=0.4.2" },
"optionalDependencies" : { "ycssmin": ">=1.0.1" },
"optionalDependencies" : { "ycssmin": ">=1.0.1", "mime": "1.2.x" },
"devDependencies" : { "diff": "~1.0" },
"scripts": {
"test": "make test"

View File

@@ -100,5 +100,12 @@
negation: #d73131;
}
#data-uri {
background-image: url(data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==);
uri: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
}
#data-uri-guess {
uri: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
}
#data-uri-ascii {
uri-1: url('data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A');
uri-2: url('data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A');
}

1
test/data/page.html Normal file
View File

@@ -0,0 +1 @@
<h1>This page is 100% Awesome.</h1>

View File

@@ -112,5 +112,14 @@
}
#data-uri {
background-image: data-uri('image/jpeg;base64', 'test/data/image.jpg');
uri: data-uri('image/jpeg;base64', 'test/data/image.jpg');
}
#data-uri-guess {
uri: data-uri('test/data/image.jpg');
}
#data-uri-ascii {
uri-1: data-uri('text/html', 'test/data/page.html');
uri-2: data-uri('test/data/page.html');
}