-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefactor-theme.js
More file actions
49 lines (39 loc) · 1.93 KB
/
Copy pathrefactor-theme.js
File metadata and controls
49 lines (39 loc) · 1.93 KB
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
const fs = require('fs');
const path = require('path');
const walkSync = (dir, filelist = []) => {
fs.readdirSync(dir).forEach(file => {
filelist = fs.statSync(dir + '/' + file).isDirectory()
? walkSync(dir + '/' + file, filelist)
: filelist.concat(dir + '/' + file);
});
return filelist;
}
const files = walkSync('./src/screens').concat(walkSync('./src/components'));
files.forEach(file => {
if (!file.endsWith('.tsx')) return;
let content = fs.readFileSync(file, 'utf8');
if (!content.includes('import { colors }')) return;
// Calculate relative path to store
const depth = file.split('/').length - 3;
const relativePrefix = depth <= 0 ? '../' : '../'.repeat(depth + 1);
const importString = `import { useThemeStore } from '${relativePrefix}store/useThemeStore';`;
content = content.replace(/import\s+\{\s*colors\s*\}\s+from\s+['"].+?theme\/colors['"];?/g, importString);
const componentRegex = /export\s+const\s+([A-Z][a-zA-Z0-9_]*)\s*=\s*\((.*?)\)\s*=>\s*\{/;
const match = content.match(componentRegex);
if (content.includes('StyleSheet.create')) {
content = content.replace(/const\s+styles\s*=\s*StyleSheet\.create\(\{/g, 'const getStyles = (colors: any) => StyleSheet.create({');
if (match) {
const injection = `\n const { colors } = useThemeStore();\n const styles = getStyles(colors);`;
content = content.replace(componentRegex, `export const $1 = ($2) => {${injection}`);
}
} else {
if (match) {
const injection = `\n const { colors } = useThemeStore();`;
content = content.replace(componentRegex, `export const $1 = ($2) => {${injection}`);
}
}
// Replace explicit constants with dynamic properties if used in default Props
content = content.replace(/colors\./g, 'colors.');
fs.writeFileSync(file, content);
console.log('Refactored: ' + file);
});