Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created July 7, 2021 06:12
Show Gist options
  • Select an option

  • Save souporserious/c71ef3aa2c4dbd7002e2f4deab754f6a to your computer and use it in GitHub Desktop.

Select an option

Save souporserious/c71ef3aa2c4dbd7002e2f4deab754f6a to your computer and use it in GitHub Desktop.
Example of web and native visitors in JSXUI.
module.exports = {
plugins: [
['@jsxui/babel-plugin', {
visitor: process.env.PLATFORM === 'native' ? require('./native') : require('./web')
}]
]
}
const buildStylesheet = template(`
const styles = StyleSheet.create(STYLES)
`)
export const nativeVistitor = {
Program(path) {
path.pushContainer(
'body',
buildStylesheet({
STYLES: t.objectExpression(
Object.entries(this.styleAttributes).map(([id, attributes]) =>
t.objectProperty(t.identifier(id), t.objectExpression(attributes))
)
),
})
)
},
JSXOpeningElement(path) {
const uid = path.node.attributes.find(
(attribute) => attribute.name.name === 'uid'
)
const attributes = path.node.attributes.filter(
(attribute) => attribute.name.name !== 'uid'
)
path.node.attributes = [
...attributes,
t.jsxAttribute(
t.jsxIdentifier('style'),
t.jSXExpressionContainer(
t.memberExpression(
t.identifier('styles'),
t.identifier(uid.value.value)
)
)
),
]
},
}
export const webVisitor = {
JSXOpeningElement(path) {
const id = path.node.attributes.find(
(attribute) => attribute.name.name === 'uid'
)
const styleAttributes = id ? this.styleAttributes[id.value.value] : null
if (styleAttributes) {
path.node.attributes.push(
t.jsxAttribute(
t.jsxIdentifier('css'),
t.jsxExpressionContainer(t.objectExpression(styleAttributes))
)
)
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment