Added script to generate icon set from css.

This commit is contained in:
Joel Arvidsson
2015-05-16 13:56:41 +02:00
parent 0e70e0c49b
commit 75ca433b23
2 changed files with 74 additions and 0 deletions

66
build.js Normal file
View File

@@ -0,0 +1,66 @@
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var glyphMapDestination = path.join(__dirname, 'glyph-maps');
if(!fs.existsSync(glyphMapDestination)) {
fs.mkdirSync(glyphMapDestination);
}
var fontDestination = path.join(__dirname, 'fonts');
if(!fs.existsSync(fontDestination)) {
fs.mkdirSync(fontDestination);
}
function extractGlyphMapFromCss(files, selectorPattern, nameIndex) {
var styleRulePattern = '(\\.[a-z0-9.:, \\n\\t-]+)\\{[^}]*content: ?"\\\\([a-f0-9]+)"[^}]*\\}';
var allStyleRules = new RegExp(styleRulePattern, 'g');
var singleStyleRules = new RegExp(styleRulePattern);
var allSelectors = new RegExp(selectorPattern, 'g');
var singleSelector = new RegExp(selectorPattern);
var glyphMap = {};
nameIndex = nameIndex || 1;
if(typeof files === 'string') {
files = [files];
}
files.forEach(function(fileName) {
var contents = fs.readFileSync(fileName, { encoding: 'utf8' });
var rules = contents.match(allStyleRules);
if(rules) {
rules.forEach(function(rule) {
var ruleParts = rule.match(singleStyleRules);
var charCode = parseInt(ruleParts[2], 16);
var selectors = ruleParts[1].match(allSelectors);
if(selectors) {
selectors.forEach(function(selector) {
var name = selector.match(singleSelector)[nameIndex];
glyphMap[name] = String.fromCharCode(charCode);
});
}
});
}
});
return glyphMap;
};
function generateIconSet(componentName, cssFiles, fontFile, fontFamily, selectorPattern) {
var glyphMap = extractGlyphMapFromCss(cssFiles, selectorPattern);
// Save glypMap as JSON for use in the component
fs.writeFileSync(
path.join(glyphMapDestination, fontFamily + '.json'),
JSON.stringify(glyphMap, null, ' ')
);
// Copy font file for easy access
fs.createReadStream(fontFile)
.pipe(fs.createWriteStream(path.join(fontDestination, fontFamily + '.ttf')));
// Generate component from our simple template
var template = fs.readFileSync('./iconSetTemplate.js', { encoding: 'utf8' });
var component = template.replace(/\{componentName\}/g, componentName).replace(/\{fontFamily\}/g, fontFamily);
fs.writeFileSync(path.join(__dirname, componentName + '.js'), component);
};

8
iconSetTemplate.js Normal file
View File

@@ -0,0 +1,8 @@
'use strict';
var createIconSet = require('./').createIconSet;
var glyphMap = require('./glyph-maps/{fontFamily}.json');
var {componentName} = createIconSet(glyphMap, '{fontFamily}');
module.exports = {componentName};