Skip to content

Instantly share code, notes, and snippets.

@ziqichen6
Created August 6, 2018 23:50
Show Gist options
  • Save ziqichen6/246e5778617224d2b4aff198dab0305d to your computer and use it in GitHub Desktop.
Save ziqichen6/246e5778617224d2b4aff198dab0305d to your computer and use it in GitHub Desktop.
jscodeshift script to replace "accessibilityTraits" and "accessibilityComponentType" with "accessibilityStates" and "accessibilityRole"
'use strict';
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
let hasChanges = false;
const elements = root.find(j.JSXElement);
let values;
let valuess;
let valuesss;
elements.forEach(path => {
const openEl = path.node.openingElement;
hasChanges = true;
for (let i = 0; i < openEl.attributes.length; i++) {
if (openEl.attributes[i].name.name === 'accessibilityComponentType') {
openEl.attributes.splice(i, 1);
}
if (openEl.attributes[i].name.name === 'accessibilityTraits') {
if (openEl.attributes[i].value.expression) {
if (openEl.attributes[i].value.expression.type === 'Literal') {
values = openEl.attributes[i].value.expression.value;
openEl.attributes[i] = j.jsxAttribute(
j.jsxIdentifier('accessibilityRole'),
j.literal(values),
);
}
}
if (openEl.attributes[i].value) {
if (
openEl.attributes[i].value &&
openEl.attributes[i].value.type === 'Literal'
) {
valuess = openEl.attributes[i].value.value;
openEl.attributes[i] = j.jsxAttribute(
j.jsxIdentifier('accessibilityRole'),
j.literal(valuess),
);
}
}
if (openEl.attributes[i].value.expression) {
if (
openEl.attributes[i].value.expression.type === 'ArrayExpression' &&
openEl.attributes[i].value.expression.elements.length === 1
) {
valuesss = openEl.attributes[i].value.expression.elements[0].value;
openEl.attributes[i] = j.jsxAttribute(
j.jsxIdentifier('accessibilityRole'),
j.literal(valuesss),
);
}
}
}
}
});
if (hasChanges) {
return root.toSource();
} else {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment