import fs from 'fs-extra' ; import path from 'path' ; import { optimize } from 'svgo' ; import { filterSvgFiles } from './utils' ; import { SvgToFontOptions } from './' ; /**
 * Generate Icon SVG Path Source
 * <font-name>.json
 */ export async function generateIconsSource ( options = { } ) { const ICONS_PATH = filterSvgFiles ( options . src ) ; const data = await buildPathsObject ( ICONS_PATH , options ) ; const outPath = path . join ( options . dist , `${ options . fontName }.json` ) ; await fs . outputFile ( outPath , `{${ data }\n}` ) ; return outPath ; } param { array } files async function buildPathsObject ( files , options = { } ) { const svgoOptions = options . svgoOptions || { } ; return Promise . all ( files . map ( async ( filepath ) => { const name = path . basename ( filepath , '.svg' ) ; const svg = fs . readFileSync ( filepath , 'utf-8' ) ; const pathStrings = optimize ( svg , { path : filepath , ... options , plugins : [ 'convertTransform' , ... ( svgoOptions . plugins || [ ] ) ] , } ) ; const str = ( pathStrings . data . match ( / d="[^"]+"/g ) || [ ] ) . map ( s => s . slice ( 3 ) ) ; return `\n"${ name }": [${ str . join ( ',\n' ) }]` ; } ) ) ; } const reactSource = ( name , source ) => `
import React from 'react';

export const ${ name } = props => (
  <svg viewBox="0 0 20 20" {...props}>${ source }</svg>
);
` ; /**
 * Generate React Icon
 * <font-name>.json
 */ export async function generateReactIcons ( options = { } ) { const ICONS_PATH = filterSvgFiles ( options . src ) ; const data = await outputReactFile ( ICONS_PATH , options ) ; const outPath = path . join ( options . dist , 'react' , 'index.js' ) ; fs . outputFileSync ( outPath , data . join ( '\n' ) ) ; return outPath ; } const capitalizeEveryWord = ( str ) => str . replace ( /-(\w)/g , ( $0 , $1 ) => $1 . toUpperCase ( ) ) . replace ( /^(\w)/g , ( $0 , $1 ) => $1 . toUpperCase ( ) ) ; async function outputReactFile ( files , options = { } ) { const svgoOptions = options . svgoOptions || { } ; return Promise . all ( files . map ( async ( filepath ) => { const name = capitalizeEveryWord ( path . basename ( filepath , '.svg' ) ) ; const svg = fs . readFileSync ( filepath , 'utf-8' ) ; const pathData = optimize ( svg , { path : filepath , ... svgoOptions , plugins : [ 'removeXMLNS' , 'removeEmptyAttrs' , 'convertTransform' , ... ( svgoOptions . plugins || [ ] ) ] } ) ; const str = ( pathData . data . match ( / d="[^"]+"/g ) || [ ] ) . map ( s => s . slice ( 3 ) ) ; const outDistPath = path . join ( options . dist , 'react' , `${ name }.js` ) ; const pathStrings = str . map ( ( d , i ) => `<path d=${ d } fillRule="evenodd" />` ) ; fs . outputFileSync ( outDistPath , reactSource ( name , pathStrings . join ( ',\n' ) ) ) ; return `export * from './${ name }';` ; } ) ) ; }