Skip to content

Instantly share code, notes, and snippets.

@seanrankin
Created August 26, 2020 15:25
Show Gist options
  • Save seanrankin/3418f718ebf90b3ab678bb33e1017d12 to your computer and use it in GitHub Desktop.
Save seanrankin/3418f718ebf90b3ab678bb33e1017d12 to your computer and use it in GitHub Desktop.
const { declare } = require('@babel/helper-plugin-utils');
const { types: t } = require('@babel/core');
const { basename, extname } = require('path');
module.exports = declare(() => {
const visitor = {
JSXOpeningElement(path, state) {
const openingElement = path.container.openingElement;
const attributes = openingElement.attributes;
const elementName =
(openingElement.name && openingElement.name.name) ||
(openingElement.name.property && openingElement.name.property.name);
let suffix = 'booty';
// Create custom labels for buttons, icons etc
if (openingElement.name.name === 'Icon') {
openingElement.attributes.map(attr => {
if (attr.name.name === 'iconName') {
console.log('-------------------------------------------');
console.log('name', attr.name.name);
console.log('value', attr.value.value);
console.log('-------------------------------------------');
suffix = attr.value.value;
}
});
}
// Ignore elements that will break things or arent needed
const blacklisted = ['Fragment', 'MuiThemeProvider', 'RootRef', 'path'];
if (blacklisted.includes(elementName)) return;
let name = 'thang';
if (state.file && state.file.opts) {
if (state.file.opts.basename) {
name = state.file.opts.basename;
} else if (state.file.opts.filename) {
name = basename(
state.file.opts.filename,
extname(state.file.opts.filename)
);
}
}
// Remove spaces, transform caps and tidy up naming
const sanitizedFileName = name.replace(' ', '').replace(/_/g, '-');
const sanitizedElName = elementName
.replace('MUI', 'mui')
.split(/(?=[A-Z])/)
.join('-')
.toLowerCase();
const sanitizedSuffix = suffix !== undefined ? `-${suffix}` : '';
let testId = `${sanitizedFileName}-${sanitizedElName}${sanitizedSuffix}`;
const dataTag = state.opts.prefix
? `data-${state.opts.prefix}-id`
: 'data-test-id';
attributes.push(
t.jSXAttribute(t.jSXIdentifier(dataTag), t.stringLiteral(testId))
);
},
};
return {
visitor,
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment