Last active
April 18, 2022 09:18
-
-
Save Innei/b8619890f4947a40d80601da9c3b5bcc to your computer and use it in GitHub Desktop.
rn-style-to-css
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-check | |
import { FontSize, FontWeight, Color, LineHeight } from './styles'; | |
const camelToSnakeCase = (str) => | |
str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`); | |
const StyleSheet = { | |
create(a) { | |
return a; | |
}, | |
}; | |
const styles = StyleSheet.create({ | |
container: { | |
paddingTop: 12, | |
}, | |
}); | |
let css = '.root * { display: flex; flex-direction: column;}\n\n'; | |
Object.entries(styles).forEach(([k, v]) => { | |
css += | |
`.${k} { | |
${Object.entries(v) | |
.map(([k, v]) => { | |
let value = v; | |
let key: string | string[] = k; | |
if (typeof key === 'string') { | |
const lowerKey = key.toLowerCase(); | |
if (lowerKey.endsWith('horizontal')) { | |
const prefix = lowerKey.replace('horizontal', ''); | |
key = [prefix + '-' + 'left', prefix + '-' + 'right']; | |
} else if (lowerKey.endsWith('vertical')) { | |
const prefix = lowerKey.replace('vertical', ''); | |
key = [prefix + '-' + 'top', prefix + '-' + 'bottom']; | |
} | |
} | |
const needAddPx = [ | |
'fontsize', | |
'lineheight', | |
'top', | |
'bottom', | |
'right', | |
'height', | |
'width', | |
'left', | |
'size', | |
'margin', | |
'padding', | |
'radius', | |
].some((key) => k.toLowerCase().includes(key) && typeof value === 'number'); | |
if (key === 'transform') { | |
// TODO | |
value = (value as any as any[]) | |
.map((obj) => { | |
return Object.keys(obj) | |
.map((key) => { | |
const unit = key == 'rotate' ? 'deg' : 'px'; | |
return `${key}(${obj[key]}${unit})`; | |
}) | |
.join(', '); | |
}) | |
.join(' '); | |
} | |
// @ts-ignore | |
return Array.isArray(key) | |
? key | |
.map( | |
(k) => `${camelToSnakeCase(k)}: ${value}${needAddPx ? 'px' : ''};` | |
) | |
.join('\n') | |
: `${camelToSnakeCase(key)}: ${value}${needAddPx ? 'px' : ''};`; | |
}) | |
.join('\n')} | |
} | |
`.trim() + '\n\n'; | |
}); | |
console.log(css); | |
// copy to clipboard macos | |
require('child_process').execSync('pbcopy', { input: css }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment