Add fontFamily transform function support for css plugin

* Support passing a transform function as css plugin's opts.fontFamily field
* Add a test case
* Update document
This commit is contained in:
akfish 2016-02-22 17:19:28 +08:00
parent 41d970704e
commit 390ae3eca7
3 changed files with 56 additions and 6 deletions

View File

@ -182,6 +182,20 @@ var fontmin = new Fontmin()
}));
```
Alternatively, a transform function can be passed as `fontFamily` option.
```js
var Fontmin = require('fontmin');
var fontmin = new Fontmin()
.use(Fontmin.css({
// ...
fontFamily: function(fontInfo, ttf) {
return "Transformed Font Family Name"
},
// ...
}));
```
### .svg2ttf()
Convert font format svg to ttf.

View File

@ -74,6 +74,32 @@ function getGlyfList(ttf) {
}
/**
* get font family name
*
* @param {Object} font info object
* @param {ttfObject} ttf ttfObject
* @param {Object} opts opts
* @return {string} font family name
*/
function getFontFamily(fontInfo, ttf, opts) {
var fontFamily = opts.fontFamily;
// Call transform function
if (typeof fontFamily === 'function') {
fontFamily = fontFamily(_.cloneDeep(fontInfo), ttf);
}
return fontFamily || ttf.name.fontFamily || fontInfo.fontFile;
}
/**
* Transform font family name
* @callback FontFamilyTransform
* @param {Object} font info object
* @param {ttfObject} ttf ttfObject
* @return {string} font family name
*/
// function(fontInfo, ttfObject) { return "Font Name"; }
/**
* css fontmin plugin
*
@ -81,7 +107,7 @@ function getGlyfList(ttf) {
* @param {boolean=} opts.glyph generate class for each glyph. default = false
* @param {boolean=} opts.base64 inject base64
* @param {string=} opts.iconPrefix icon prefix
* @param {string=} opts.fontFamily fontFamily
* @param {(string|FontFamilyTransform)=} opts.fontFamily fontFamily
* @return {Object} stream.Transform instance
* @api public
*/
@ -143,9 +169,7 @@ module.exports = function (opts) {
}
// font family
fontInfo.fontFamily = opts.fontFamily
|| ttfObject.name.fontFamily
|| fontFile;
fontInfo.fontFamily = getFontFamily(fontInfo, ttfObject, opts);
// rewrite font family as filename
if (opts.asFileName) {
@ -180,4 +204,3 @@ module.exports = function (opts) {
});
};

View File

@ -65,7 +65,10 @@ before(function (done) {
glyph: true,
base64: true,
fontPath: './',
local: true
local: true,
fontFamily: function(font, ttf) {
return ttf.name.fontFamily + " - Transformed";
}
}))
.dest(destPath);
@ -289,5 +292,15 @@ describe('css plugin', function () {
}
});
it('dest css should have transformed @font-family name', function() {
var content = fs.readFileSync(destFile + '.css', {
encoding: 'utf-8'
});
var m = content.match(/font-family: \s*"(.*?)"/),
fontFamily = m[1];
expect(fontFamily).to.be.a('string')
.that.match(/\s-\sTransformed$/);
});
});