Skip to content

Commit

Permalink
Added script to generate icon set from css.
Browse files Browse the repository at this point in the history
  • Loading branch information
oblador committed May 16, 2015
1 parent 0e70e0c commit 75ca433
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
66 changes: 66 additions & 0 deletions build.js
Original file line number Diff line number Diff line change
@@ -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 changes: 8 additions & 0 deletions iconSetTemplate.js
Original file line number Diff line number Diff line change
@@ -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};

0 comments on commit 75ca433

Please sign in to comment.