This repository has been archived by the owner on Dec 29, 2023. It is now read-only.
forked from goopscoop/svg-to-react-cli
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
executable file
·183 lines (154 loc) · 5.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env node
'use strict';
// Vendor includes
const chalk = require('chalk');
const fs = require('fs');
const yargs = require('yargs');
const path = require('path');
const HTMLtoJSX = require('htmltojsx');
const jsdom = require('jsdom-no-contextify');
const SVGtoJSX = require('svg-to-jsx');
// Language files
const content = require('./lang/en');
// Local includes
const createComponentName = require('./src/createComponentName');
const formatSVG = require('./src/formatSVG');
const generateComponent = require('./src/generateComponent');
const printErrors = require('./src/output').printErrors;
const removeStyle = require('./src/removeStyle');
const replaceAllStrings = require('./src/replaceAllStrings');
// Argument setup
const args = yargs
.option('dir', { alias: 'd', default: false })
.option('format', { default: true })
.option('output', { alias: 'o' })
.option('rm-style', { default: false })
.option('force', { alias: 'f', default: false }).argv;
// Resolve arguments
const firstArg = args._[0];
const newFileName = args._[1] || 'MyComponent';
const outputPath = args.output;
const directoryPath = args.dir;
const rmStyle = args.rmStyle;
const format = args.format;
// Bootstrap base variables
const converter = new HTMLtoJSX({ createClass: false });
const svg = `./${firstArg}.svg`;
let fileCount = 0;
const writeFile = (processedSVG, fileName) => {
let file;
let filesWritten = 0;
if (outputPath) {
file = path.resolve(process.cwd(), outputPath, `${fileName}.js`);
} else {
file = path.resolve(process.cwd(), `${fileName}.js`);
}
fs.writeFile(file, processedSVG, { flag: args.force ? 'w' : 'wx' }, function(
err
) {
if (err) {
if (err.code === 'EEXIST') {
printErrors(
`Output file ${file} already exists. Use the force (--force) flag to overwrite the existing files`
);
} else {
printErrors(`Output file ${file} not writable`);
}
return;
}
filesWritten++;
console.log('File written to -> ' + file);
if (filesWritten === fileCount) {
console.log(
`${filesWritten} components created. That must be some kind of record`
);
console.log();
console.log(content.processCompleteText);
console.log();
}
});
};
const runUtil = (fileToRead, fileToWrite) => {
fs.readFile(fileToRead, 'utf8', function(err, file) {
if (err) {
printErrors(err);
return;
}
let output = file;
jsdom.env(output, (err, window) => {
const body = window.document.getElementsByTagName('body')[0];
if (rmStyle) {
removeStyle(body);
}
// Add width and height
// The order of precedence of how width/height is set on to an element is as follows:
// 1st - passed in props are always priority one. This gives run time control to the container
// 2nd - svg set width/height is second priority
// 3rd - if no props, and no svg width/height, use the viewbox width/height as the width/height
// 4th - if no props, svg width/height or viewbox, simlpy set it to 50px/50px
let defaultWidth = '50px';
let defaultheight = '50px';
if (body.firstChild.hasAttribute('viewBox')) {
const [minX, minY, width, height] = body.firstChild
.getAttribute('viewBox')
.split(/[,\s]+/);
defaultWidth = width;
defaultheight = height;
}
if (!body.firstChild.hasAttribute('width')) {
body.firstChild.setAttribute('width', defaultWidth);
}
if (!body.firstChild.hasAttribute('height')) {
body.firstChild.setAttribute('height', defaultheight);
}
// Add generic props attribute to parent element, allowing props to be passed to the svg
// such as className
body.firstChild.setAttribute(':props:', '');
// Now that we are done with manipulating the node/s we can return it back as a string
output = body.innerHTML;
// Convert from HTML to JSX
// output = converter.convert(output);
SVGtoJSX(output).then(jsx => {
// Convert any html tags to react-native-svg tags
jsx = replaceAllStrings(jsx);
// Wrap it up in a React component
jsx = generateComponent(jsx, fileToWrite);
writeFile(jsx, fileToWrite);
});
});
});
};
const runUtilForAllInDir = () => {
fs.readdir(path.resolve(process.cwd(), directoryPath), (err, files) => {
if (err) {
return console.log(err);
}
files.forEach((file, i) => {
const resolvedFile = path.resolve(process.cwd(), directoryPath, file);
const extension = path.extname(resolvedFile);
const fileName = path.basename(resolvedFile);
if (extension === '.svg') {
// variable instantiated up top
const componentName = createComponentName(file, fileName);
runUtil(resolvedFile, componentName);
fileCount++;
}
});
});
};
// Exit out early arguments
if (args.help) {
console.log(content.helptext);
process.exit(1);
}
if (args.example) {
console.log(content.exampleText);
process.exit(1);
}
// Main entry point
if (directoryPath) {
runUtilForAllInDir();
} else {
fileCount++;
runUtil(svg, newFileName);
}