Browse Source

Create style attribute codemod

main
GreatBearShark 1 year ago
parent
commit
e41f72c2eb
  1. 2
      src/components/community-dropdown.tsx
  2. 2
      src/components/post-listing.tsx
  3. 18
      src/components/sample.tsx
  4. 76
      transform.js

2
src/components/community-dropdown.tsx

@ -90,7 +90,7 @@ export class CommunityDropdown extends Component<
>
{!this.state.loading && (
<div className="dropdown-content">
<div style="display:flex">
<div style={{ display: 'flex' }}>
<input
className="dropdown-filter form-control"
placeholder="Filter"

2
src/components/post-listing.tsx

@ -252,7 +252,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
>
<Icon
className="icon thumbnail mini-overlay"
style="margin-top: 4px"
style={{ marginTop: '4px' }}
name="link"
/>
</span>

18
src/components/sample.tsx

@ -0,0 +1,18 @@
import React from 'react';
function Sample() {
return (
<div>
<div style={{
display: "inline-block",
marginTop: "6px"
}}>
Incorrect format
</div>
<div style={{ display: 'inline-block', marginTop: '6px' }}>
Correct format
</div>
</div>
);
}

76
transform.js

@ -0,0 +1,76 @@
module.exports.parser = 'tsx';
const formatStringToCamelCase = str => {
const splitted = str.split("-");
if (splitted.length === 1) return splitted[0];
return (
splitted[0] +
splitted
.slice(1)
.map(word => word[0].toUpperCase() + word.slice(1))
.join("")
);
};
export const getStyleObjectFromString = str => {
const style = {};
str.split(";").forEach(el => {
const [property, value] = el.split(":");
if (!property) return;
const formattedProperty = formatStringToCamelCase(property.trim());
style[formattedProperty] = value.trim();
});
return style;
};
function transformStyleAttribute(path) {
const attributeName = path.node.name.name
const attributeType = path.node.value.type
if (attributeName === 'style' && attributeType === 'StringLiteral') {
// TRANSFORM
const styleString = path.node.value.value;
const styleObject = getStyleObjectFromString(styleString);
path.node.value = {
type: 'JSXExpressionContainer',
expression: {
type: 'ObjectExpression',
properties: Object.entries(styleObject).map(([key, value]) => {
return {
"type": "Property",
"key": {
"type": "Identifier",
"name": key
},
"value": {
"type": "Literal",
"value": value,
"raw": `'${value}'`
},
"kind": "init",
};
}
)
}
}
}
}
module.exports = function (fileInfo, api, options) {
const j = api.jscodeshift;
// transform `fileInfo.source` here
// ...
// return changed source
// console.log(Object.keys(api.jscodeshift))
// console.log(j.JSXIdentifier)
const root = j(fileInfo.source);
// console.log({ root })
const attributes = root.find(j.JSXAttribute)
attributes.forEach(transformStyleAttribute)
// const identifier
return root.toSource();
};
Loading…
Cancel
Save