-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
92 lines (78 loc) · 2.64 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
var through2 = require('through2');
var path = require('path');
var mime = require('mime');
var Vinyl = require('vinyl');
var PluginError = require('plugin-error');
var mimes = {
woff: 'application/font-woff',
woff2: 'application/font-woff2',
ttf: 'application/x-font-truetype',
eot: 'application/vnd.ms-fontobject',
otf: 'application/x-font-opentype',
svg: 'image/svg+xml'
};
var cssFormats = {
ttf: 'truetype',
otf: false
};
module.exports = function(custom) {
var fonts = [],
options = { name: 'font', style: 'normal', weight: 400, formats: ['woff', 'woff2'], stretch: 'normal', display : 'auto' },
output = null;
for(var attr in custom) { options[attr] = custom[attr] }
function process(file) {
var mime_type = mime.lookup(file.path);
var mime_ext = mime.extension(mime_type);
if(!mimes[mime_ext]) return;
var cssFormat = cssFormats[mime_ext];
if(cssFormat === undefined) cssFormat = mime_ext;
if(cssFormat !== false) cssFormat = 'format("' + cssFormat + '")';
return {
format: mime_ext,
cssFormat: cssFormat,
compile: function() {
return 'url("data:' + mime_type + ';base64,' + file.contents.toString('base64') + '")' +
(cssFormat ? ' ' + cssFormat : '');
}
}
}
var transform = function (file, encoding, cb) {
if(file.isBuffer()) {
var font = process(file);
if(font && options.formats.indexOf(font.format) != -1) {
fonts.push(font);
if(!output) {
output = new Vinyl({
cwd: file.cwd,
base: file.base,
path: path.join(file.base, options.name + '.css')
});
}
}
} else if(file.isStream()) {
this.emit('error', new PluginError('gulp-inline-fonts', 'Streaming is not supported'));
}
cb();
}
var flush = function(cb) {
// if there are no matched files
if(!output) return cb();
var fontGroups = fonts.reduce(function(acc, font) {
acc[font.cssFormat ? 1 : 0].push(font);
return acc;
}, [[], []]);
var content = '@font-face { ' +
'font-family: "' + options.name + '"; ' +
'font-style: ' + options.style + '; ' +
'font-stretch: ' + options.stretch + '; ' +
'font-weight: ' + options.weight + '; ' +
'font-display: ' + options.display + '; ' +
fontGroups[0].map(function(f) { return 'src: ' + f.compile() + '; '}).join('') +
'src: local("' + options.name + '"), ' + fontGroups[1].map(function(f) { return f.compile() }).join(', ') + '; ' +
'}';
output.contents = new Buffer(content);
this.push(output);
cb();
}
return through2.obj({}, transform, flush);
};