-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
95 lines (70 loc) · 2.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var spritesmith = require('spritesmith');
var path = require('path');
var _ = require('lodash');
var uniq = _.uniq;
var extend = _.extend;
var escapeRegExp = function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var createCSSPropertiesFor = function(coords) {
return 'background-position: ' + -coords.x + 'px ' + -coords.y + 'px';
};
var normalizeRest = function(rest) {
rest = rest.replace(/(\s+|\n|\r)/, '');
return rest ? ' ' + rest : rest;
};
var normalizeDelimiter = function(delimiter) {
return delimiter === '}' ? ';\n}' : ';';
};
var extractPaths = function(urlRegex, content) {
var paths = [];
var match;
while (match = urlRegex.exec(content)) {
paths.push(match[1]);
}
return paths;
};
var removeBasePath = function(prefixRegex, currentPath) {
return currentPath.replace(prefixRegex, '');
};
var findPaths = function(prefixRegex, urlRegex, content) {
return extractPaths(urlRegex, content).map(function(item) {
return removeBasePath(prefixRegex, item);
});
};
var createFullPath = function(basePath, currentPath) {
return path.join(basePath, currentPath);
};
var replaceUrlsWithSprite = function(urlRegex, prefixRegex, options, content, coords) {
return content.replace(urlRegex, function(match, path, rest, delimiter) {
var coord = coords[createFullPath(options.path, removeBasePath(prefixRegex, path))];
var css = createCSSPropertiesFor(coord);
rest = normalizeRest(rest);
delimiter = normalizeDelimiter(delimiter);
return 'url(' + options.name + ')' + rest + '; ' + css + delimiter;
});
};
var defaultOptions = {
name: 'sprite.png',
path: 'images/sprites',
prefix: '/images/sprites/'
};
var getFullPaths = function(prefixRegex, urlRegex, basePath, cssContent) {
var paths = uniq(findPaths(prefixRegex, urlRegex, cssContent));
return paths.map(function(item) {
return createFullPath(basePath, item);
});
};
var sprite = function(options, cssContent, callback) {
options = extend({}, defaultOptions, options);
var prefixRegex = new RegExp(escapeRegExp(options.prefix));
var urlRegex = new RegExp("url\\((?:'|\")?(" + escapeRegExp(options.prefix) + ".*?)(?:'|\")?\\)(?:(.*?|\\n*?|\\r*?))(;|})", 'gi');
var fullPaths = getFullPaths(prefixRegex, urlRegex, options.path, cssContent);
spritesmith({ src: fullPaths }, function(err, result) {
if (err) { return callback(err); }
var finalCSS = replaceUrlsWithSprite(urlRegex, prefixRegex, options, cssContent, result.coordinates);
var image = result.image;
callback(null, finalCSS, image);
});
};
module.exports = sprite;