diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..3c078e9 --- /dev/null +++ b/.babelrc @@ -0,0 +1,5 @@ +{ + "presets": [ + "es2015" + ] +} diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..db1f22b --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ +node_modules: + npm install + +dist: + mkdir dist + +dist/icons.json: node_modules dist icons icons/*.svg + ./node_modules/.bin/babel-node bin/build-json.js diff --git a/bin/build-json.js b/bin/build-json.js new file mode 100755 index 0000000..0280c81 --- /dev/null +++ b/bin/build-json.js @@ -0,0 +1,71 @@ +/** + * @file Builds `icons.json` from `icons` directory. + */ + +/* eslint-disable import/no-extraneous-dependencies */ +import fs from 'fs'; +import path from 'path'; +import RSVP from 'rsvp'; +import Svgo from 'svgo'; +import parse5 from 'parse5'; + +const svgFiles = fs.readdirSync(path.resolve(__dirname, '../icons')) + .filter(file => path.extname(file) === '.svg'); + +buildIconsObject(svgFiles) + .then(icons => { + fs.writeFileSync( + path.resolve(__dirname, '../dist/icons.json'), + JSON.stringify(icons), + ); + }); + +/** + * Build an icons object in the format: `{ : }`. + * @param {string[]} svgFiles - A list of file names. + * @returns {RSVP.Promise} + */ +function buildIconsObject(svgFiles) { + const icons = {}; + + svgFiles.forEach(svgFile => { + const svg = fs.readFileSync(path.resolve(__dirname, '../icons', svgFile), 'utf8'); + const key = path.basename(svgFile, '.svg'); + + icons[key] = optimizeSvg(svg) + .then(optimizedSvg => getSvgContent(optimizedSvg)); + }); + + return RSVP.hash(icons); +} + +/** + * Optimize SVG with `svgo`. + * @param {string} svg - An SVG string. + * @returns {RSVP.Promise} + */ +function optimizeSvg(svg) { + // configure svgo + const svgo = new Svgo({ + plugins: [ + { convertShapeToPath: false }, + { mergePaths: false }, + { removeAttrs: { attrs: '(fill|stroke.*)' } }, + ], + }); + + return new RSVP.Promise(resolve => { + svgo.optimize(svg, ({ data }) => resolve(data)); + }); +} + +/** + * Get content between opening and closing `` tags. + * @param {string} svg - An SVG string. + * @returns {string} + */ +function getSvgContent(svg) { + const fragment = parse5.parseFragment(svg); + const content = parse5.serialize(fragment.childNodes[0]); + return content; +}