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

feat: babel allow for inline nested objects, spreads and destructuring #553

Merged
merged 2 commits into from
Feb 3, 2025
Merged
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
112 changes: 110 additions & 2 deletions plugin/__tests__/dependencies.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,58 @@ pluginTester({
)
`
},
{
title: 'Should correctly detect inline spread',
code: `
import { View, Text } from 'react-native'
import { StyleSheet } from 'react-native-unistyles'

export const Example = () => {
return (
<View style={styles.container}>
<Text style={styles.container2}>Hello world</Text>
</View>
)
}

const styles = StyleSheet.create(theme => ({
container: {
...theme.components.container
},
container2: {
...theme.components.text
}
}))
`,
output: `
import { Text } from 'react-native-unistyles/components/native/Text'
import { View } from 'react-native-unistyles/components/native/View'

import { StyleSheet } from 'react-native-unistyles'

export const Example = () => {
return (
<View style={styles.container}>
<Text style={styles.container2}>Hello world</Text>
</View>
)
}

const styles = StyleSheet.create(
theme => ({
container: {
...theme.components.container,
uni__dependencies: [0]
},
container2: {
...theme.components.text,
uni__dependencies: [0]
}
}),
664955283
)
`
},
{
title: 'Should correctly detect inline theme dependencies',
code: `
Expand All @@ -724,7 +776,7 @@ pluginTester({

const styles = StyleSheet.create(theme => ({
container: theme.components.container,
container2: theme.components.text
container2: theme.components.text.nested.deep
}))
`,
output: `
Expand All @@ -744,11 +796,67 @@ pluginTester({
const styles = StyleSheet.create(
theme => ({
container: { ...theme.components.container, uni__dependencies: [0] },
container2: { ...theme.components.text, uni__dependencies: [0] }
container2: { ...theme.components.text.nested.deep, uni__dependencies: [0] }
}),
664955283
)
`
},
{
title: 'Should correctly detect destructured dependencies',
code: `
import { View, Text } from 'react-native'
import { StyleSheet } from 'react-native-unistyles'

export const Example = () => {
return (
<View style={styles.container}>
<Text style={styles.container2}>Hello world</Text>
</View>
)
}

const styles = StyleSheet.create(({ components: { test }}, { insets: { ime }, screen: { height }, statusBar }) => ({
container: {
backgroundColor: test
},
container2: {
paddingBottom: ime,
height,
width: statusBar.width
}
}))
`,
output: `
import { Text } from 'react-native-unistyles/components/native/Text'
import { View } from 'react-native-unistyles/components/native/View'

import { StyleSheet } from 'react-native-unistyles'

export const Example = () => {
return (
<View style={styles.container}>
<Text style={styles.container2}>Hello world</Text>
</View>
)
}

const styles = StyleSheet.create(
({ components: { test } }, { insets: { ime }, screen: { height }, statusBar }) => ({
container: {
backgroundColor: test,
uni__dependencies: [0]
},
container2: {
paddingBottom: ime,
height,
width: statusBar.width,
uni__dependencies: [14, 6, 12]
}
}),
664955283
)
`
}
]
})
12 changes: 12 additions & 0 deletions plugin/common.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
function getIdentifierNameFromExpression(t, memberExpression) {
if (t.isIdentifier(memberExpression)) {
return [memberExpression.name]
}

if (t.isSpreadElement(memberExpression)) {
return [getIdentifierNameFromExpression(t, memberExpression.argument)].flat()
}

if (t.isObjectProperty(memberExpression)) {
return [getIdentifierNameFromExpression(t, memberExpression.value)].flat()
}

if (t.isMemberExpression(memberExpression)) {
if (memberExpression.computed) {
return [
Expand Down
23 changes: 7 additions & 16 deletions plugin/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { addUnistylesImport, isInsideNodeModules } = require('./import')
const { hasStringRef } = require('./ref')
const { isUnistylesStyleSheet, analyzeDependencies, addStyleSheetTag, getUnistyles, isKindOfStyleSheet, addThemeDependencyToMemberExpression } = require('./stylesheet')
const { isUnistylesStyleSheet, analyzeDependencies, addStyleSheetTag, getUnistyles, isKindOfStyleSheet, maybeAddThemeDependencyToMemberExpression, addThemeDependencyToMemberExpression, getStyleSheetLocalNames } = require('./stylesheet')
const { extractVariants } = require('./variants')
const { REACT_NATIVE_COMPONENT_NAMES, REPLACE_WITH_UNISTYLES_PATHS, REPLACE_WITH_UNISTYLES_EXOTIC_PATHS, NATIVE_COMPONENTS_PATHS } = require('./consts')
const { handleExoticImport } = require('./exotic')
Expand Down Expand Up @@ -156,23 +156,15 @@ module.exports = function ({ types: t }) {
const propertyValues = getUnistyles(t, property)

propertyValues.forEach(propertyValue => {
analyzeDependencies(t, state, property.key.name, propertyValue)
analyzeDependencies(t, state, property.key.name, propertyValue, [], [])
})
}
})
}

// Function passed to StyleSheet.create (e.g., theme => ({ container: {} }))
if (t.isArrowFunctionExpression(arg) || t.isFunctionExpression(arg)) {
const params = arg.params
const hasTheme = params.length >= 1
const hasMiniRuntime = params.length === 2
const themeLocalName = hasTheme
? params[0].name
: undefined
const miniRuntimeLocalName = hasMiniRuntime
? params[1].name
: undefined
const localNames = getStyleSheetLocalNames(t, arg)
const body = t.isBlockStatement(arg.body)
? arg.body.body.find(statement => t.isReturnStatement(statement)).argument
: arg.body
Expand All @@ -183,15 +175,14 @@ module.exports = function ({ types: t }) {
if (t.isObjectProperty(property)) {
const propertyValues = getUnistyles(t, property)

// special case for non object/function properties
// maybe user used inlined theme? ({ container: theme.components.container })
if (propertyValues.length === 0 && t.isMemberExpression(property.value)) {
if (property.value.object.object.name === themeLocalName) {
addThemeDependencyToMemberExpression(t, property)
}
if (propertyValues.length === 0 && maybeAddThemeDependencyToMemberExpression(t, property, localNames.theme)) {
addThemeDependencyToMemberExpression(t, property)
}

propertyValues.forEach(propertyValue => {
analyzeDependencies(t, state, property.key.name, propertyValue, themeLocalName, miniRuntimeLocalName)
analyzeDependencies(t, state, property.key.name, propertyValue, localNames.theme, localNames.miniRuntime)
})
}
})
Expand Down
101 changes: 96 additions & 5 deletions plugin/stylesheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,71 @@ function addStyleSheetTag(t, path, state) {
callee.container.arguments.push(t.numericLiteral(uniqueId))
}

function getStyleSheetLocalNames(t, functionArg) {
const params = functionArg.params
const hasTheme = params.length >= 1
const hasMiniRuntime = params.length === 2
const getProperty = (property, allowNested) => {
if (t.isIdentifier(property.value)) {
return property.value.name
}

if (!t.isObjectPattern(property.value)) {
return undefined
}

if (allowNested) {
return property.value.properties.flatMap(getProperty)
}

// we can force allow nested only for insets
const hasIme = property.value.properties.find(property => property.key.name === 'ime')
const lastKeyValue = property.value.properties.flatMap(getProperty)

if (hasIme) {
return lastKeyValue
}

return `${property.key.name}.${lastKeyValue}`
}
const getLocalNames = (param, allowNested) => {
if (t.isObjectPattern(param)) {
return param.properties
.flatMap(property => getProperty(property, allowNested))
.filter(Boolean)
}


if (t.isIdentifier(param)) {
return [param.name]
}

return []
}

return {
theme: hasTheme ? getLocalNames(params[0], true) : [],
miniRuntime: hasMiniRuntime ? getLocalNames(params[1], false) : []
}
}

function maybeAddThemeDependencyToMemberExpression(t, property, themeLocalNames) {
if (t.isIdentifier(property)) {
return themeLocalNames.includes(property.name)
}

if (t.isObjectProperty(property)) {
return maybeAddThemeDependencyToMemberExpression(t, property.value, themeLocalNames)
}

if (t.isMemberExpression(property)) {
return maybeAddThemeDependencyToMemberExpression(t, property.object, themeLocalNames)
}
}


/** @param {import('./index').UnistylesPluginPass} state */
function analyzeDependencies(t, state, name, unistyleObj, themeName, rtName) {
function analyzeDependencies(t, state, name, unistyleObj, themeNames, rtNames) {
const debugMessage = deps => {
if (state.opts.debug) {
const mappedDeps = deps
Expand All @@ -78,16 +141,42 @@ function analyzeDependencies(t, state, name, unistyleObj, themeName, rtName) {
const dependencies = []

Object.values(unistyle).forEach(uni => {
const identifier = getIdentifierNameFromExpression(t, uni.value)
const identifiers = getIdentifierNameFromExpression(t, uni)

if (identifier.includes(themeName)) {
if (themeNames.some(name => identifiers.some(id => id === name))) {
dependencies.push(UnistyleDependency.Theme)
}

if (identifier.includes(rtName)) {
const matchingRtNames = rtNames.reduce((acc, name) => {
if (name.includes('.')) {
const key = name.split('.').at(0)

if (identifiers.some(id => name.includes(id))) {
return [
...acc,
key
]
}

return acc
}


if (identifiers.some(id => id === name)) {
return [
...acc,
name
]
}

return acc
}, [])

if (matchingRtNames.length > 0) {
const propertyNames = getSecondPropertyName(t, uni.value)

propertyNames
matchingRtNames
.concat(propertyNames)
.filter(Boolean)
.forEach(propertyName => {
switch (propertyName) {
Expand Down Expand Up @@ -235,5 +324,7 @@ module.exports = {
addStyleSheetTag,
getUnistyles,
isKindOfStyleSheet,
getStyleSheetLocalNames,
maybeAddThemeDependencyToMemberExpression,
addThemeDependencyToMemberExpression
}