Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a better configuration file + more options #2

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 69 additions & 9 deletions helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,83 @@ const input = require('input')
const currentPath = process.cwd()
const configFileName = '.svgrc'
const path = require('path')
const configPath = path.resolve(currentPath, configFileName)
const configPath = path.resolve(currentPath, "svg-inliner.json")
const chalk = require('chalk')

const DEFAULT_CONFIG = {
createHtml: undefined,
exportType: undefined,
iconsDirectory: undefined,
}

module.exports = {
getUserSettings: async () => {
if (fs.existsSync(configPath)) {
const exportType = fs.readFileSync(configPath)

return exportType
} else {
let config = DEFAULT_CONFIG

// load config if exists
if(fs.existsSync(configPath)) {

let file = fs.readFileSync(configPath)
try {
let data = JSON.parse(file);

// asign loaded values
for (var key in data) {
config[key] = data[key]
}
} catch (e) {
console.log(chalk.red('✘ Error while loading configuration file.'))
console.log(' Changes may overwrite your existing configuration. \n')
}
}

let prevConfig = Object.assign({}, config) // create object copy for detecting changes

// get option for export type
if(config.exportType === undefined) {
const options = [
'React component',
'String'
{ name: 'React Component', value: 'react_component' },
{ name: 'String', value: 'string' },
]
const selectedOption = await input.select('Export as ', options)
fs.writeFileSync(configPath, selectedOption)
return selectedOption
config.exportType = selectedOption

console.log('');
}

// get option for documentation generation
if(config.createHtml === undefined) {
const options = [
{ name: 'Generate HTML', value: true },
{ name: 'Skip Generation', value: false },
]
const selectedOption = await input.select('Generate Documentation:', options)
config.createHtml = selectedOption

console.log('');
}

if(config.iconsDirectory === undefined) {

let data = await input.text('SVG File location [relative to current path]', { default: '/' })

config.iconsDirectory = `/${data.indexOf('/') == 0 ? data.replace('/', '') : data.indexOf('./') == 0 ? data.replace('./', '') : data}`

console.log('');
}

// save config if changed
if(JSON.stringify(prevConfig) != JSON.stringify(config)) {
try {
fs.writeFileSync(configPath, JSON.stringify(config))
console.log(chalk.green('✔ Configuration file sucessfully saved. \n'))
} catch (e) {
console.log(chalk.red('✘ Error while saving configuration file. \n'))
}
}

return config
},
toPascalCase: (string) => {
return `${string}`
Expand Down
149 changes: 77 additions & 72 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,81 +9,86 @@ const svgTransformer = require('./transform/index.js')

const { toPascalCase, getUserSettings } = require('./helpers')

const currentPath = path.resolve(process.cwd())

const exportDir = `${currentPath}`
const indexFile = `${exportDir}/all-icons.js`
const iconsDir = `${currentPath}`
const htmlIconsMap = `${exportDir}/all-icons.html`

const logo = require('./logo')
console.log(logo(ver))

fs.readdir(iconsDir, async function (err, items) {
if (err) {
console.error(err)
process.exitCode(1)
return
}

const settings = await getUserSettings()

const files = items.filter((file, i) => file.indexOf('.svg') > 0 && i < 10)

const svgs = await Promise.all(files.map(async (file, i) => {
const fName = file.split('.')[0]
const fileName = toPascalCase(fName)
process.stdout.write(`${fileName} | `)

const svgTag = fs.readFileSync(`${iconsDir}/${file}`, 'utf8')

// const optimisedSvg = await svgo.optimize(svgTag)
const optimisedSvg = await svgTransformer(svgTag)

console.log(optimisedSvg)

const asString = `${
optimisedSvg.replace('<svg ', `\n<svg class='svg-icon ${fName}-svg' `)
}`
const asRC = `props => {
const {className,...rest}=props
const cName = (className||'') + ' svg-icon ${fName}-svg'
return (${optimisedSvg
.replace('<svg ', `\n<svg className={cName} {...rest} `)
})}`

return new Promise((resolve, reject) => {
resolve({
fileName,
asRC,
asString
getUserSettings().then(settings => {

const currentPath = path.resolve(process.cwd())

const exportDir = `${currentPath}`
const indexFile = `${exportDir}/all-icons.js`
const iconsDir = `${currentPath}${settings.iconsDirectory}`
const htmlIconsMap = `${exportDir}/all-icons.html`

const logo = require('./logo')
console.log(logo(ver))

fs.readdir(iconsDir, async function (err, items) {
if (err) {
console.error(err)
process.exitCode(1)
return
}

const files = items.filter((file, i) => file.indexOf('.svg') > 0 && i < 10)

const svgs = await Promise.all(files.map(async (file, i) => {
const fName = file.split('.')[0]
const fileName = toPascalCase(fName)
process.stdout.write(`${fileName} | `)

const svgTag = fs.readFileSync(`${iconsDir}/${file}`, 'utf8')

// const optimisedSvg = await svgo.optimize(svgTag)
const optimisedSvg = await svgTransformer(svgTag)

// console.log(optimisedSvg)

const asString = `${
optimisedSvg.replace('<svg ', `\n<svg class='svg-icon ${fName}-svg' `)
}`
const asRC = `props => {
const {className,...rest}=props
const cName = (className||'') + ' svg-icon ${fName}-svg'
return (${optimisedSvg
.replace('<svg ', `\n<svg className={cName} {...rest} `)
})}`

return new Promise((resolve, reject) => {
resolve({
fileName,
asRC,
asString
})
})
}))

const svgsExport = svgs.map(({ fileName, asRC, asString }) => {
return `export const ${fileName} = ${settings.exportType === 'string' ? (`\`${asString}\``) : asRC}`
})
}))

const svgsExport = svgs.map(({ fileName, asRC, asString }) => {
return `export const ${fileName} = ${settings === 'String' ? (`\`${asString}\``) : asRC}`
if(settings.createHtml) { // generate html documentation if enabled

const iconsHtml = svgs.map(obj => `
<div class='icon-def'>
<span class='icon-img'>${obj.asString}</span>
<span class='icon-name'>${obj.fileName}</span>
</div>
`)

fs.writeFileSync(htmlIconsMap, htmlTemplate(`
<div class='icons-list'>
${iconsHtml.join('')}
</div>
`, ver))
}

fs.writeFileSync(indexFile, `import React from 'react'\n${svgsExport.join('\n')}\n`)

console.log()
console.log('---------------------------------------------')
console.log(`${chalk.green('✔')} Exported ${svgsExport.length} svgs to all-icons.js`)
if(settings.createHtml) console.log(`${chalk.green('✔')} Icons map: ${chalk.blueBright(htmlIconsMap)}`)
console.log('---------------------------------------------')
console.log()
})

const iconsHtml = svgs.map(obj => `
<div class='icon-def'>
<span class='icon-img'>${obj.asString}</span>
<span class='icon-name'>${obj.fileName}</span>
</div>
`)

fs.writeFileSync(htmlIconsMap, htmlTemplate(`
<div class='icons-list'>
${iconsHtml.join('')}
</div>
`, ver))

fs.writeFileSync(indexFile, `import React from 'react'\n${svgsExport.join('\n')}\n`)

console.log()
console.log('---------------------------------------------')
console.log(`${chalk.green('✔')} Exported ${svgsExport.length} svgs to all-icons.js`)
console.log(`${chalk.green('✔')} Icons map: ${chalk.blueBright(htmlIconsMap)}`)
console.log('---------------------------------------------')
console.log()
})
11 changes: 8 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"cli"
],
"author": "alessio carnevale",
"contributors": ["Raphael Dick (https://github.com/raphael-dick/)"],
"license": "ISC",
"dependencies": {
"chalk": "^2.4.2",
Expand All @@ -24,7 +25,8 @@
"lodash.camelcase": "^4.3.0",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"svg-parser": "^2.0.2",
"prettier": "^1.18.2",
"svg-parser": "^1.0.6",
"svgo": "^1.3.0"
},
"devDependencies": {},
Expand Down
11 changes: 6 additions & 5 deletions transform/lib/formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const TEMPLATES = {
`,
functional: (svg, name) => `
import React from "react";

export const ${name} = '${svg}'
`
}
Expand All @@ -24,11 +24,12 @@ const TEMPLATES = {
*/
function reactify (svg, { type = 'functional', name = '' }) {
const compile = TEMPLATES[type](svg, name)
const component = compile({
svg
})
// const component = compile({
// svg
// })
// return component

return component
return svg
}

/**
Expand Down