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

refactor(react-jss): React JSS will use hooks add styles to nodes. #526

Merged
merged 2 commits into from
Jan 5, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ describe('Generates media, pseudo and normal styles', () => {

expect(cssFile).not.toBeDefined()
expect(jsFile).toBeDefined()
expect(jsFile.content).toContain(`className={props.classes['container']}`)

expect(jsFile.content).toContain(`const classes = useStyles()`)
expect(jsFile.content).toContain(`className={classes['container']}`)
expect(jsFile.content).toContain(`container: {`)
expect(jsFile.content).toContain(`width: '100px'`)
expect(jsFile.content).toContain(`display: 'none'`)
Expand Down Expand Up @@ -179,7 +181,7 @@ describe('Add referenced styles even when direct styles are not present on node'

expect(cssFile).not.toBeDefined()
expect(jsFile).toBeDefined()
expect(jsFile.content).toContain(`className={props.classes['container']}`)
expect(jsFile.content).toContain(`className={classes['container']}`)
expect(jsFile.content).toContain(`container: {`)
expect(jsFile.content).not.toContain(`width: '100px'`)
expect(jsFile.content).toContain(`display: 'none'`)
Expand Down
11 changes: 4 additions & 7 deletions packages/teleport-plugin-react-jss/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { createReactJSSPlugin } from '../src/index'
describe('plugin-react-jss', () => {
const plugin = createReactJSSPlugin({
styleChunkName: 'jss-chunk',
exportChunkName: 'export-chunk',
})
const componentChunk: ChunkDefinition = {
name: 'jsx-component',
Expand Down Expand Up @@ -81,16 +80,14 @@ describe('plugin-react-jss', () => {
}

const { dependencies, chunks } = await plugin(structure)
const { injectSheet } = dependencies
const { createUseStyles } = dependencies

expect(Object.keys(dependencies).length).toBeGreaterThan(0)
expect(injectSheet.type).toBe('package')
expect(injectSheet.path).toBe('react-jss')
expect(createUseStyles.type).toBe('package')
expect(createUseStyles.path).toBe('react-jss')

expect(chunks.length).toBe(3)
expect(chunks.length).toBe(2)
expect(chunks[1].type).toBe(ChunkType.AST)
expect(chunks[1].name).toBe('jss-chunk')
expect(chunks[2].type).toBe(ChunkType.AST)
expect(chunks[2].name).toBe('export-chunk')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ describe('Referenced Styles on Node', () => {
const result = await plugin(structure)
const { chunks, dependencies } = result

expect(chunks.length).toBe(3)
expect(chunks.length).toBe(2)
expect(Object.keys(dependencies).length).toBe(1)
expect(dependencies.injectSheet.path).toBe('react-jss')
expect(dependencies.createUseStyles.path).toBe('react-jss')
})

it('References a style from project and adds, Media and pseudo from referencedStyles', async () => {
Expand Down Expand Up @@ -149,9 +149,9 @@ describe('Referenced Styles on Node', () => {
const result = await plugin(structure)
const { chunks, dependencies } = result

expect(chunks.length).toBe(3)
expect(chunks.length).toBe(2)
expect(Object.keys(dependencies).length).toBe(2)
expect(dependencies.injectSheet.path).toBe('react-jss')
expect(dependencies.createUseStyles.path).toBe('react-jss')
expect(dependencies.useProjectStyles.path).toBe('../style')
expect(dependencies.useProjectStyles.meta.namedImport).toBe(true)
})
Expand Down
72 changes: 37 additions & 35 deletions packages/teleport-plugin-react-jss/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ interface JSSConfig {
styleChunkName?: string
importChunkName?: string
componentChunkName: string
exportChunkName: string
jssDeclarationName?: string
classAttributeName?: string
}
const EXPORT_IDENTIFIER = 'createUseStyles'

export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config) => {
const {
componentChunkName = 'jsx-component',
importChunkName = 'import-local',
styleChunkName = 'jss-style-definition',
exportChunkName = 'export',
jssDeclarationName = 'style',
jssDeclarationName = 'useStyles',
classAttributeName = 'className',
} = config || {}

Expand All @@ -38,12 +38,11 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
return structure
}

// @ts-ignore
const propsPrefix = componentChunk.meta.dynamicRefPrefix.prop
const jsxNodesLookup = componentChunk.meta.nodesLookup
const jssStyleMap: Record<string, unknown> = {}
let isProjectReferenced: boolean = false
let isTokenReferenced = false
let isPropsReferenced = false

UIDLUtils.traverseElements(node, (element) => {
const { style, key, referencedStyles } = element
Expand All @@ -55,12 +54,16 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
const root = jsxNodesLookup[key]
const className = StringUtils.camelCaseToDashCase(key)
const classNamesToAppend: string[] = []
if (style && Object.keys(style).length > 0) {
const { transformedStyles, tokensUsed } = generatePropSyntax(style)

if (Object.keys(style || {}).length > 0) {
const { transformedStyles, tokensUsed, propsUsed } = generatePropSyntax(style)
jssStyleMap[className] = transformedStyles
if (tokensUsed) {
isTokenReferenced = true
}
if (propsUsed) {
isPropsReferenced = true
}
appendClassname = true
}

Expand All @@ -76,12 +79,15 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
}

if (condition.conditionType === 'screen-size') {
const { transformedStyles, tokensUsed } = generatePropSyntax(
const { transformedStyles, tokensUsed, propsUsed } = generatePropSyntax(
styleRef.content.styles
)
if (tokensUsed) {
isTokenReferenced = true
}
if (propsUsed) {
isPropsReferenced = true
}
jssStyleMap[className] = {
...(jssStyleMap[className] as Record<string, string>),

Expand All @@ -90,12 +96,15 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
}

if (condition.conditionType === 'element-state') {
const { transformedStyles, tokensUsed } = generatePropSyntax(
const { transformedStyles, tokensUsed, propsUsed } = generatePropSyntax(
styleRef.content.styles
)
if (tokensUsed) {
isTokenReferenced = true
}
if (propsUsed) {
isPropsReferenced = true
}
jssStyleMap[className] = {
...(jssStyleMap[className] as Record<string, string>),
[`&:${condition.content}`]: transformedStyles,
Expand Down Expand Up @@ -137,7 +146,7 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
}

if (appendClassname) {
classNamesToAppend.push(`${propsPrefix}.classes['${className}']`)
classNamesToAppend.push(`classes['${className}']`)
}

if (classNamesToAppend.length > 1) {
Expand All @@ -154,7 +163,7 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
const isPropsInjected = astNode.init.params?.some(
(prop: types.Identifier) => prop.name === 'props'
)
if (!isPropsInjected) {
if (!isPropsInjected && isPropsReferenced) {
astNode.init.params.push(types.identifier('props'))
}

Expand All @@ -177,17 +186,29 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
},
}
// @ts-ignore
astNode.init.body.body.unshift(createStylesHookDecleration())
astNode.init.body.body.unshift(
createStylesHookDecleration('projectStyles', 'useProjectStyles')
)
}

if (!Object.keys(jssStyleMap).length) {
return structure
}

dependencies.injectSheet = {
// @ts-ignore
astNode.init.body.body.unshift(
isPropsReferenced
? createStylesHookDecleration('classes', 'useStyles', 'props')
: createStylesHookDecleration('classes', 'useStyles')
)

dependencies[EXPORT_IDENTIFIER] = {
type: 'package',
path: 'react-jss',
version: '10.4.0',
meta: {
namedImport: true,
},
}

chunks.push({
Expand All @@ -197,31 +218,12 @@ export const createReactJSSPlugin: ComponentPluginFactory<JSSConfig> = (config)
linkAfter: [importChunkName],
content: ASTBuilders.createConstAssignment(
jssDeclarationName,
ASTUtils.objectToObjectExpression(jssStyleMap)
types.callExpression(types.identifier(EXPORT_IDENTIFIER), [
ASTUtils.objectToObjectExpression(jssStyleMap),
])
),
})

const exportChunk = chunks.find((chunk) => chunk.name === exportChunkName)

const componentName = UIDLUtils.getComponentClassName(uidl)
const exportStatement = ASTBuilders.createReactJSSDefaultExport(
componentName,
jssDeclarationName
)

if (exportChunk) {
exportChunk.content = exportStatement
exportChunk.linkAfter = [importChunkName, styleChunkName]
} else {
chunks.push({
type: ChunkType.AST,
fileType: FileType.JS,
name: exportChunkName,
content: exportStatement,
linkAfter: [importChunkName, styleChunkName],
})
}

return structure
}

Expand Down
20 changes: 15 additions & 5 deletions packages/teleport-plugin-react-jss/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { UIDLStyleValue } from '@teleporthq/teleport-types'

export const generatePropSyntax = (style: Record<string, UIDLStyleValue>) => {
let tokensUsed = false
let propsUsed = false
return {
transformedStyles: UIDLUtils.transformDynamicStyles(style, (styleValue) => {
switch (styleValue.content.referenceType) {
case 'prop':
propsUsed = true
return new ParsedASTNode(
ASTBuilders.createArrowFunctionWithMemberExpression('props', styleValue.content.id)
)
Expand All @@ -29,14 +31,22 @@ export const generatePropSyntax = (style: Record<string, UIDLStyleValue>) => {
}
}),
tokensUsed,
propsUsed,
}
}

export const createStylesHookDecleration = (types = t) => {
return types.variableDeclaration('const', [
export const createStylesHookDecleration = (
assignee: string,
hookName: string,
dynamicValueIdentifier?: string,
types = t
) =>
types.variableDeclaration('const', [
types.variableDeclarator(
t.identifier('projectStyles'),
t.callExpression(t.identifier('useProjectStyles'), [])
t.identifier(assignee),
t.callExpression(
t.identifier(hookName),
dynamicValueIdentifier ? [types.identifier(dynamicValueIdentifier)] : []
)
),
])
}