forked from frontendbeast/gulp-svg-spritesheet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
348 lines (284 loc) · 11.5 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
'use strict';
var cheerio = require('cheerio'),
events = require('events'),
fs = require('fs'),
gutil = require('gulp-util'),
mkdirp = require('mkdirp'),
mustache = require('mustache'),
packetr = require('./lib/packer.growing'),
path = require('path'),
through2 = require('through2');
// Consts
var PLUGIN_NAME = 'gulp-svg-spritesheet';
// Options
var defaults = {
cssPathNoSvg: '', // Leave blank if you dont want to specify a fallback
cssPathSvg: './test.svg', // CSS path to generated SVG
demoDest: '', // Leave blank if you don't want a demo file
demoSrc: '../demo.tpl', // The souce or the demo template
padding: 0, // Add some padding between sprites
pixelBase: 16, // Used to calculate em/rem values
positioning: 'vertical', // vertical, horizontal, diagonal or packed
templateSrc: '../template.tpl', // The source of the CSS template
templateDest: './sprite.scss',
units: 'px', // px, em or rem
x: 0, // Starting X position
y: 0, // Starting Y position
imgName: 'sprite.svg'
};
// Sorting functions from Jake Gordon's bin packing algorithm demo
// https://github.com/jakesgordon/bin-packing
var sort = {
w : function (a,b) { return b.w - a.w; },
h : function (a,b) { return b.h - a.h; },
max : function (a,b) { return Math.max(b.w, b.h) - Math.max(a.w, a.h); },
min : function (a,b) { return Math.min(b.w, b.h) - Math.min(a.w, a.h); },
height : function (a,b) { return sort.msort(a, b, ['h', 'w']); },
width : function (a,b) { return sort.msort(a, b, ['w', 'h']); },
maxside : function (a,b) { return sort.msort(a, b, ['max', 'min', 'h', 'w']); },
msort: function(a, b, criteria) {
var diff, n;
for (n = 0 ; n < criteria.length ; n++) {
diff = sort[criteria[n]](a,b);
if (diff !== 0)
return diff;
}
return 0;
}
};
// This is where the magic happens
var spriteSVG = function(options) {
options = options || {};
// Extend our defaults with any passed options
for (var key in defaults) {
options[key] = options[key] || defaults[key];
}
// Create one SVG to rule them all, our sprite sheet
var $ = cheerio.load('<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>', { xmlMode: true }),
$sprite = $('svg'),
// This data will be passed to our template
data = {
cssPathSvg: options.cssPathSvg,
height: 0,
sprites: [],
units: options.units,
width: 0,
imgName: options.imgName
},
eventEmitter = new events.EventEmitter(),
self,
x = options.x,
y = options.y;
// When a template file is loaded, render it
eventEmitter.on("loadedTemplate", renderTemplate);
// Generate relative em/rem untis from pixels
function pxToRelative(value) {
return value / options.pixelBase;
}
// Load a template file and then render it
function loadTemplate(src, dest, cb) {
fs.readFile(src, function(err, contents) {
if(err) {
new gutil.PluginError(PLUGIN_NAME, err);
}
var file = {
contents: contents.toString(),
data: data,
dest: dest
};
eventEmitter.emit("loadedTemplate", file, cb);
});
}
// Position sprites using Jake Gordon's bin packing algorithm
// https://github.com/jakesgordon/bin-packing
function packSprites(cb) {
var packer = new GrowingPacker();
// Get coordinates of sprites
packer.fit(data.sprites);
// For each sprite
for (var i in data.sprites) {
var sprite = data.sprites[i];
// Create, initialise and populate an SVG
var spriteAttr = {
'height': sprite.h,
'viewBox': sprite.viewBox,
'width': sprite.w,
'x': Math.ceil(sprite.fit.x)+options.padding,
'y': Math.ceil(sprite.fit.y)+options.padding
};
if (sprite.fill){
Object.assign(spriteAttr, {'fill': sprite.fill});
}
var $svg = $('<svg/>')
.attr(spriteAttr)
.append(sprite.file);
// Check and set parent SVG width
if(sprite.fit.x+sprite.w+options.padding>data.width) {
data.width = Math.ceil(sprite.fit.x+sprite.w+options.padding);
}
// Check and set sprite sheet height
if(sprite.fit.y+sprite.h+options.padding>data.height) {
data.height = Math.ceil(sprite.fit.y+sprite.h+options.padding);
}
// Round up coordinates and add padding
sprite.h = Math.ceil(sprite.h);
sprite.w = Math.ceil(sprite.w);
sprite.x = -Math.abs(Math.ceil(sprite.fit.x))-options.padding;
sprite.y = -Math.abs(Math.ceil(sprite.fit.y))-options.padding;
// Convert to relative units if required
if(options.units!=='px') {
sprite.h = pxToRelative(sprite.h);
sprite.w = pxToRelative(sprite.w);
sprite.x = pxToRelative(sprite.x);
sprite.y = pxToRelative(sprite.y);
}
// Add the SVG to the sprite sheet
$sprite.append($svg);
}
// Save the sprite sheet
saveSpriteSheet(cb);
}
function positionSprites(cb) {
// For each sprite
for (var i in data.sprites) {
var sprite = data.sprites[i];
// Add padding
sprite.x = x+options.padding;
sprite.y = y+options.padding;
// Create, initialise and populate an SVG
var svgSpriteAttrs = {
'height': sprite.h,
'viewBox': sprite.viewBox,
'width': sprite.w,
'x': Math.ceil(sprite.x),
'y': Math.ceil(sprite.y)
};
if (sprite.fill) {
Object.assign(svgSpriteAttrs, {'fill': sprite.fill});
}
var $svg = $('<svg/>')
.attr(svgSpriteAttrs)
.append(sprite.file);
// Round up coordinates
sprite.h = Math.ceil(sprite.h);
sprite.w = Math.ceil(sprite.w);
sprite.x = -Math.abs(Math.ceil(sprite.x));
sprite.y = -Math.abs(Math.ceil(sprite.y));
// Increment x/y coordinates and set sprite sheet height/width
if(options.positioning==='horizontal' || options.positioning==='diagonal') {
x+=sprite.w+options.padding;
data.width+=sprite.w+options.padding;
if(options.positioning!=='diagonal' && data.height<sprite.h+options.padding) {
data.height = sprite.h+options.padding;
}
}
if(options.positioning==='vertical' || options.positioning==='diagonal') {
y+=sprite.h+options.padding;
data.height+=sprite.h+options.padding;
if(options.positioning!=='diagonal' && data.width<sprite.w+options.padding) {
data.width = sprite.w+options.padding;
}
}
// Convert to relative units if required
if(options.units!=='px') {
sprite.h = pxToRelative(sprite.h);
sprite.w = pxToRelative(sprite.w);
sprite.x = pxToRelative(sprite.x);
sprite.y = pxToRelative(sprite.y);
}
// Add the SVG to the sprite sheet
$sprite.append($svg);
}
// Save the sprite sheet
saveSpriteSheet(cb);
}
function processSVG(file, encoding, cb) {
// Ignore empty files
if (file.isNull()) {
return;
}
// We don't do streaming
if (file.isStream()) {
return cb(new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported'));
}
// We're using the filename as the CSS class name
var filename = path.basename(file.relative, path.extname(file.relative)),
// Load the file contents
$file = cheerio.load(file.contents.toString('utf8'), {xmlMode: true})('svg'),
viewBox = $file.attr('viewBox'),
coords = viewBox.split(" "),
width = $file.attr('width') || coords[2],
height = $file.attr('height') || coords[3];
// Set sprite data to be used by the positioning function
var sprite = {
fileName: filename,
file: $file.contents(),
h: parseFloat(height),
padding: options.padding,
// Round up coordinates to avoid chopping off edges
viewBox: Math.ceil(coords[0])+" "+Math.ceil(coords[1])+" "+Math.ceil(coords[2])+" "+Math.ceil(coords[3]),
w: parseFloat(width)
};
if ($file.attr('fill') !== undefined) {
Object.assign(sprite, {fill: $file.attr('fill')});
}
// Add the sprite to our array
data.sprites.push(sprite);
// Move on to processSprites()
cb();
}
function processSprites(cb) {
// Save this for referencing in positioning functions
self = this;
// Sort the sprites so the biggest are first to avoid this issue:
// https://github.com/jakesgordon/bin-packing/blob/master/js/packer.growing.js#L10
data.sprites.sort(sort.maxside);
// Lay out the sprites
if(options.positioning==='packed') {
packSprites(cb);
} else {
positionSprites(cb);
}
}
// Render our template and then save the file
function renderTemplate(file, cb) {
var compiled = mustache.render(file.contents, file.data);
mkdirp(path.dirname(file.dest), function(){
fs.writeFile(file.dest, compiled, cb);
});
}
// Final processing of sprite sheet then we return file to gulp pipe
function saveSpriteSheet(cb) {
// Add padding to even edges up
data.height+=options.padding;
data.width+=options.padding;
// If there is a non-svg fallback send the path to the template
if(options.cssPathNoSvg) {
data.cssPathNoSvg = options.cssPathNoSvg;
}
// Set the sprite sheet width, height and viewbox
$sprite.attr({
'height': data.height,
'viewBox': '0 0 '+data.width+' '+data.height,
'width': data.width
});
// Convert to relative units if required
if(options.units!=='px') {
data.height = pxToRelative(data.height);
data.width = pxToRelative(data.width);
}
// Create a file to pipe back to gulp
var file = new gutil.File({path: './', contents: new Buffer($.xml())});
// Pipe it baby!
self.push(file);
// cb will be executed after css file will be rendered and created
// Save our CSS template file
loadTemplate(options.templateSrc, options.templateDest, cb);
// If a demo file is required, save that too
if(options.demoDest) {
loadTemplate(options.demoSrc, options.demoDest, cb);
}
}
return through2.obj(processSVG, processSprites);
};
module.exports = spriteSVG;