ember-codemod-remove-global-styles
Version:
Codemod to localize global styles
99 lines (98 loc) • 3.55 kB
JavaScript
function extractClasses(value) {
return value.split(/\s+/).filter(Boolean);
}
export class Processor {
classes = new Set();
errors = [];
print() {
const { classes, errors } = this;
return {
classes: Array.from(classes),
errors,
};
}
processConcatStatement(nodeValue) {
nodeValue.parts.forEach((part) => {
switch (part.type) {
case 'MustacheStatement': {
this.processMustacheStatement(part);
break;
}
case 'TextNode': {
this.processTextNode(part);
break;
}
}
});
}
processMustacheStatement(nodeValue) {
switch (nodeValue.path.type) {
case 'PathExpression': {
switch (nodeValue.path.original) {
case 'if':
case 'unless': {
if (nodeValue.params[1]?.type === 'StringLiteral') {
this.processStringLiteral(nodeValue.params[1]);
}
if (nodeValue.params[2]?.type === 'StringLiteral') {
this.processStringLiteral(nodeValue.params[2]);
}
break;
}
default: {
const isLocalClass = nodeValue.path.original.startsWith('styles.');
if (!isLocalClass) {
this.errors.push(`Could not analyze {{${nodeValue.path.original}}} in template, line ${nodeValue.loc.start.line}.`);
}
}
}
break;
}
case 'StringLiteral': {
this.processStringLiteral(nodeValue.path);
break;
}
}
}
processStringLiteral(nodeValue) {
const classNames = extractClasses(nodeValue.original);
classNames.forEach((className) => {
this.classes.add(className);
});
}
processSubExpression(nodeValue) {
switch (nodeValue.path.type) {
case 'PathExpression': {
switch (nodeValue.path.original) {
case 'if':
case 'unless': {
if (nodeValue.params[1]?.type === 'StringLiteral') {
this.processStringLiteral(nodeValue.params[1]);
}
if (nodeValue.params[2]?.type === 'StringLiteral') {
this.processStringLiteral(nodeValue.params[2]);
}
break;
}
default: {
const isLocalClass = nodeValue.path.original.startsWith('styles.');
if (!isLocalClass) {
this.errors.push(`Could not analyze {{${nodeValue.path.original}}} in template, line ${nodeValue.loc.start.line}.`);
}
}
}
break;
}
case 'StringLiteral': {
this.processStringLiteral(nodeValue.path);
break;
}
}
}
processTextNode(nodeValue) {
const classNames = extractClasses(nodeValue.chars);
classNames.forEach((className) => {
this.classes.add(className);
});
}
}