diff --git a/README.md b/README.md index d9251b9..d2e2452 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/plugins/css.js b/plugins/css.js index 0bfe1e8..77df363 100644 --- a/plugins/css.js +++ b/plugins/css.js @@ -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) { }); }; - diff --git a/test/font.js b/test/font.js index e886d82..a8597b6 100644 --- a/test/font.js +++ b/test/font.js @@ -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$/); + }); + });