|
| 1 | +#!/usr/bin/env node |
| 2 | +/* eslint-env node */ |
| 3 | + |
| 4 | +const fs = require('fs'); |
| 5 | +const path = require('path'); |
| 6 | +const SVGO = require('svgo'); |
| 7 | +const camelCase = require('lodash/camelCase'); |
| 8 | +const chalk = require('chalk'); |
| 9 | + |
| 10 | +const startTime = Date.now(); |
| 11 | + |
| 12 | +const svgo = new SVGO({ |
| 13 | + plugins: [ |
| 14 | + { cleanupIDs: false }, |
| 15 | + { removeViewBox: false } |
| 16 | + ] |
| 17 | +}); |
| 18 | + |
| 19 | +// Each of these functions are applied to the SVG source in turn. I'd add svgo here too if it didn't return a Promise. |
| 20 | +const replacements = [ |
| 21 | + ensureClosingTag, |
| 22 | + insertTitle, |
| 23 | + fixNamespaces, |
| 24 | + fixDataAttributes, |
| 25 | + fixSvgAttributes, |
| 26 | + fixStyleAttributes |
| 27 | +]; |
| 28 | + |
| 29 | +const svgs = fs.readdirSync('./src/components/icon/assets').filter(f => f.endsWith('.svg')); |
| 30 | + |
| 31 | +for (const svg of svgs) { |
| 32 | + const filepath = `./src/components/icon/assets/${svg}`; |
| 33 | + const iconName = path.basename(svg, '.svg'); |
| 34 | + |
| 35 | + const rawSvgSource = fs.readFileSync(filepath, 'utf8'); |
| 36 | + |
| 37 | + svgo.optimize(rawSvgSource, { path: filepath }).then(function (result) { |
| 38 | + const modifiedSvg = replacements.reduce((svg, eachFn) => eachFn(svg), result.data); |
| 39 | + |
| 40 | + const { defaultProps, finalSvg } = extractDefaultProps(filepath, modifiedSvg); |
| 41 | + const reactComponent = renderTemplate({ |
| 42 | + name: camelCase(iconName), |
| 43 | + svg: finalSvg, |
| 44 | + defaultProps |
| 45 | + }); |
| 46 | + |
| 47 | + fs.writeFileSync(`./src/components/icon/iconComponents/${iconName}.js`, reactComponent); |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +console.log(chalk.green.bold(`✔ Finished generating React components from SVGs (${ Date.now() - startTime } ms)`)); |
| 52 | + |
| 53 | +/** |
| 54 | + * Ensures that the root <svg> element is not self-closing. This is to generically handle empty.svg, |
| 55 | + * whose source would otherwise break the other transforms. |
| 56 | + * @param svg |
| 57 | + */ |
| 58 | +function ensureClosingTag(svg) { |
| 59 | + return svg.replace(/\/>$/, '></svg>'); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Adds a title element to the SVG, which svgo will have stripped out. |
| 64 | + */ |
| 65 | +function insertTitle(svg) { |
| 66 | + const index = svg.indexOf('>') + 1; |
| 67 | + return svg.slice(0, index) + '<title>{ title } </title>' + svg.slice(index); |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Makes XML namespaces work with React. |
| 72 | + */ |
| 73 | +function fixNamespaces(svg) { |
| 74 | + return svg.replace(/xmlns:xlink/g, 'xmlnsXlink').replace(/xlink:href/g, 'xlinkHref'); |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Camel-cases data attributes. |
| 79 | + */ |
| 80 | +function fixDataAttributes(svg) { |
| 81 | + return svg.replace(/(data-[\w-]+)="([^"]+)"/g, (_, attr, value) => `${ camelCase(attr)}="${ value }"`); |
| 82 | +} |
| 83 | + |
| 84 | +/** |
| 85 | + * Camel-cases SVG attributes. |
| 86 | + */ |
| 87 | +function fixSvgAttributes(svg) { |
| 88 | + return svg.replace(/(fill-rule|stroke-linecap|stroke-linejoin)="([^"]+)"/g, (_, attr, value) => `${ camelCase(attr)}="${ value }"`); |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * Turns inline styles as strings into objects. |
| 93 | + */ |
| 94 | +function fixStyleAttributes(svg) { |
| 95 | + return svg.replace(/(style)="([^"]+)"/g, (_, attr, value) => `style={${ JSON.stringify(cssToObj(value)) }}`); |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * Extracts the attributes on an SVG and returns them as default props for the React component, |
| 100 | + * plus a modified SVG with those attributes stripped out. Also injects a props spread to that |
| 101 | + * any other props passed to the React components are set on the SVG. |
| 102 | + * @param {string} filename the name of the SVG |
| 103 | + * @param {string} svg the SVG source |
| 104 | + * @return {{defaultProps: {}, finalSvg: string}} |
| 105 | + */ |
| 106 | +function extractDefaultProps(filename, svg) { |
| 107 | + const endIndex = svg.indexOf('>'); |
| 108 | + const attrString = svg.slice(4, endIndex).trim(); |
| 109 | + |
| 110 | + const defaultProps = {}; |
| 111 | + |
| 112 | + for (const pair of attrString.match(/(\w+)="([^"]+)"/g)) { |
| 113 | + const [, name, value] = pair.match(/^(\w+)="([^"]+)"$/); |
| 114 | + defaultProps[camelCase(name)] = value; |
| 115 | + } |
| 116 | + |
| 117 | + defaultProps.title = path.basename(filename, '.svg').replace(/_/g, ' ') + ' icon'; |
| 118 | + |
| 119 | + const finalSvg = '<svg { ...props }' + svg.slice(endIndex); |
| 120 | + |
| 121 | + return { |
| 122 | + defaultProps, |
| 123 | + finalSvg |
| 124 | + }; |
| 125 | +} |
| 126 | + |
| 127 | +/** |
| 128 | + * Generates the final React component. |
| 129 | + */ |
| 130 | +function renderTemplate({ name, svg, defaultProps }) { |
| 131 | + return `// This is a generated file. Proceed with caution. |
| 132 | +/* eslint-disable */ |
| 133 | +import React from 'react'; |
| 134 | +
|
| 135 | +const ${name} = ({ title, ...props }) => ${ svg }; |
| 136 | +
|
| 137 | +${name}.defaultProps = ${JSON.stringify(defaultProps, null, 2)}; |
| 138 | +
|
| 139 | +export default ${name}; |
| 140 | +`; |
| 141 | +} |
| 142 | + |
| 143 | + |
| 144 | +/** |
| 145 | + * Hack to convert a piece of CSS into an object |
| 146 | + */ |
| 147 | +function cssToObj(css) { |
| 148 | + const o = {}; |
| 149 | + css.split(';').filter(el => !!el).forEach(el => { |
| 150 | + const s = el.split(':'); |
| 151 | + const key = camelCase(s.shift().trim()); |
| 152 | + const value = s.join(':').trim(); |
| 153 | + o[key] = value; |
| 154 | + }); |
| 155 | + |
| 156 | + return o; |
| 157 | +} |
0 commit comments