Skip to content

Commit

Permalink
feat: add codemod
Browse files Browse the repository at this point in the history
  • Loading branch information
sashuk committed Sep 1, 2023
1 parent 4fea587 commit 2611f0a
Show file tree
Hide file tree
Showing 7 changed files with 295 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/good-houses-end.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@toptal/picasso-codemod': minor
---

- add `spacing-values` codemod. Please run the codemod (`npx @toptal/picasso-codemod v39.0.0`) to replace spacing property values of `Container` and `Dropdown` components with BASE-aligned property values according to the https://github.com/toptal/picasso/blob/master/docs/decisions/18-spacings.md. Property values that do not have BASE counterpart or are complex expressions have to be updated manually, codemod outputs the list of such cases for convenience. Please run linter or prettier to align updated code with project code style.
9 changes: 9 additions & 0 deletions packages/picasso-codemod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ Codemods do not guarantee the code format preservation. Therefore be sure to run

## Included Scripts


### v39.0.0

Replaces spacing property values of `Container` and `Dropdown` components with BASE-aligned property values according to the https://github.com/toptal/picasso/blob/master/docs/decisions/18-spacings.md. Property values that do not have BASE counterpart or are complex expressions have to be updated manually, codemod outputs the list of such cases for convenience. Please run linter or prettier to align updated code with project code style.

```sh
npx @toptal/picasso-codemod v39.0.0
```

### v36.0.0

Replaces all imports of RichTextEditor related components to `@toptal/picasso-rich-text-editor` and updates package.json with a new version of `@toptal/picasso`, `@toptal/picasso-rich-text-editor` and `@toptal/picasso-forms`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import React from 'react'
import { Container } from '@toptal/picasso'

const test = 'large'
const booleanVariable = true
const extraProps = { align: 'left '}

export default () => (
<>
<Container top='small' someProp='small'>Content</Container>
<Container right={test} someProp={1.5}>Content</Container>
<Container bottom={1.5}>Content</Container>
<Container left={1.6}>Content</Container>
<Container top={booleanVariable ? 'small' : 1.5}>Content</Container>
<Container {...extraProps}>Content</Container>
<Dropdown
someProp='small'
offset={{
top: 'small',
right: test,
bottom: 3,
left: 1.6
}}
content={
<Menu>
<Menu.Item>Menu item 1</Menu.Item>
</Menu>
}
>
Dropdown
</Dropdown>
</>
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import React from 'react'
import { Container } from '@toptal/picasso'

import { SPACING_4, SPACING_6, SPACING_12 } from '@toptal/picasso/utils';

const test = 'large'
const booleanVariable = true
const extraProps = { align: 'left '}

export default () => (
<>
<Container top={SPACING_4} someProp='small'>Content</Container>
<Container right={test} someProp={1.5}>Content</Container>
<Container bottom={SPACING_6}>Content</Container>
<Container left={1.6}>Content</Container>
<Container top={booleanVariable ? SPACING_4 : SPACING_6}>Content</Container>
<Container {...extraProps}>Content</Container>
<Dropdown
someProp='small'
offset={{
top: SPACING_4,
right: test,
bottom: SPACING_12,
left: 1.6
}}
content={
<Menu>
<Menu.Item>Menu item 1</Menu.Item>
</Menu>
}
>
Dropdown
</Dropdown>
</>
)
3 changes: 3 additions & 0 deletions packages/picasso-codemod/src/v39.0.0/__tests__/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineTest } from 'jscodeshift/src/testUtils'

defineTest(__dirname, 'spacing-values', {}, 'default', { parser: 'tsx' })
1 change: 1 addition & 0 deletions packages/picasso-codemod/src/v39.0.0/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './spacing-values'
205 changes: 205 additions & 0 deletions packages/picasso-codemod/src/v39.0.0/spacing-values.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import type { API, Transform } from 'jscodeshift'

const AFFECTED_COMPONENTS = ['Container', 'Dropdown']
const AFFECTED_ATTRIBUTES = [
'top',
'right',
'bottom',
'left',
'padded',
'gap',
'offset',
]

// TODO: replace with exported spacings
const sizeToSpacingConstant: Record<string, string> = {
xsmall: 'SPACING_2',
small: 'SPACING_4',
medium: 'SPACING_6',
large: 'SPACING_8',
xlarge: 'SPACING_10',
}

const numericValueToSpacingConstants = [
{ value: 0, name: 'SPACING_0' },
{ value: 0.25, name: 'SPACING_1' },
{ value: 0.5, name: 'SPACING_2' },
{ value: 0.75, name: 'SPACING_3' },
{ value: 1, name: 'SPACING_4' },
{ value: 1.5, name: 'SPACING_6' },
{ value: 2, name: 'SPACING_8' },
{ value: 2.5, name: 'SPACING_10' },
{ value: 3, name: 'SPACING_12' },
]

type TransformationOptions = {
api: API
reportUnfixableCase: () => void
}

const getNodeForSizeStringConstant = (
node: any,
{ api }: TransformationOptions
) => {
const spacingConstant = node.value
const spacingName = sizeToSpacingConstant[spacingConstant]

if (!spacingName) {
throw new Error(
`Unable to match "${spacingConstant}" size string constant to BASE spacing`
)
}

return {
node: api.jscodeshift.identifier(spacingName),
requiredImports: [spacingName],
}
}

const getNodeForNumber = (
node: any,
{ api, reportUnfixableCase }: TransformationOptions
) => {
const numericValue = node.value
const spacing = numericValueToSpacingConstants.find(
({ value }) => value === numericValue
)

if (spacing) {
return {
node: api.jscodeshift.identifier(spacing.name),
requiredImports: [spacing.name],
}
}
reportUnfixableCase()

return { node, requiredImports: [] }
}

// TODO: not fixed cases

const getUpdatedNode = (node: any, options: TransformationOptions) => {
const { reportUnfixableCase } = options
let requiredImports: string[] = []

if (node.type === 'StringLiteral') {
;({ node, requiredImports } = getNodeForSizeStringConstant(node, options))
} else if (node.type === 'NumericLiteral') {
;({ node, requiredImports } = getNodeForNumber(node, options))
} else if (node.type === 'ObjectExpression') {
const updatedProperties = node.properties.map(property => {
const { node: propertyNode, requiredImports: propertyRequiredImports } =
getUpdatedNode(property.value, options)

property.value = propertyNode
requiredImports = [...requiredImports, ...propertyRequiredImports]

return property
})

node.properties = updatedProperties
} else if (node.type === 'ConditionalExpression') {
const { node: consequentNode, requiredImports: consequentRequiredImports } =
getUpdatedNode(node.consequent, options)
const { node: alternateNode, requiredImports: alternateRequiredImports } =
getUpdatedNode(node.alternate, options)

requiredImports = [
...consequentRequiredImports,
...alternateRequiredImports,
]
node.consequent = consequentNode
node.alternate = alternateNode
} else {
reportUnfixableCase()
}

return { node, requiredImports }
}

const transform: Transform = (file, api) => {
let spacingsToImport: string[] = []

const unfixableCases = []
const j = api.jscodeshift
const ast = j(file.source)

ast
.find(j.JSXElement)
.filter(
path =>
AFFECTED_COMPONENTS.indexOf(path.node.openingElement.name.name) > -1
)
.forEach(element => {
const updatedElementAttributes =
element.node.openingElement.attributes.map(attribute => {
const attributeName = attribute.name?.name

if (
!attributeName ||
AFFECTED_ATTRIBUTES.indexOf(attributeName) === -1
) {
return attribute
}

const options = {
api,
reportUnfixableCase: () => {
unfixableCases.push({
componentName: element.value.openingElement.name.name,
attributeName,
location: `${file.path}:${element.value.loc?.start.line}`,
})
},
}

let node, requiredImports

if (attribute.value.type === 'JSXExpressionContainer') {
;({ node, requiredImports } = getUpdatedNode(
attribute.value.expression,
options
))
attribute.value.expression = node
} else {
;({ node, requiredImports } = getUpdatedNode(
attribute.value,
options
))
attribute.value = api.jscodeshift.jsxExpressionContainer(node)
}

spacingsToImport = [...spacingsToImport, ...requiredImports]

return attribute
})

element.node.openingElement.attributes = updatedElementAttributes
})

if (spacingsToImport.length > 0) {
const newImport = j.importDeclaration(
Array.from(new Set(spacingsToImport)).map(spacing =>
j.importSpecifier(j.identifier(spacing))
),
j.stringLiteral('@toptal/picasso/utils')
)

ast
.find(j.ImportDeclaration)
.filter(path => path.node.source.value === '@toptal/picasso')
.insertAfter(newImport)

if (unfixableCases.length > 0) {
unfixableCases.forEach(({ componentName, attributeName, location }) => {
process.stdout.write(
`\x1b[33mManual update required for ${componentName}.${attributeName} in ${location}\x1b[0m\n`
)
})
}
}

return ast.toSource({ quote: 'single' })
}

export default transform

0 comments on commit 2611f0a

Please sign in to comment.