@atlaskit/eslint-plugin-design-system
Version:
The essential plugin for use with the Atlassian Design System.
89 lines (85 loc) • 2.78 kB
JavaScript
import { getSourceCode } from '@atlaskit/eslint-utils/context-compat';
import { findVariable } from '@atlaskit/eslint-utils/find-variable';
export class UnusedCssMapChecker {
constructor(cssMapObject, context, cssMapCallNode) {
this.cssMapObject = cssMapObject;
this.cssMapCallNode = cssMapCallNode;
this.report = context.report;
this.context = context;
}
checkForUnusedStyles() {
// Get all defined style keys
const definedStyles = new Map();
for (const property of this.cssMapObject.properties) {
if (property.type === 'Property' && property.key.type === 'Identifier') {
definedStyles.set(property.key.name, property);
}
}
if (definedStyles.size === 0) {
return;
}
// Find the variable that holds the cssMap result
const cssMapVariable = this.findCssMapVariable();
if (!cssMapVariable) {
return;
}
// Early return if no references - all styles are unused
if (cssMapVariable.references.length === 0) {
for (const [styleName, property] of definedStyles) {
this.report({
node: property.key,
messageId: 'unusedCssMapStyle',
data: {
styleName
}
});
}
return;
}
const usedStyles = new Set();
for (const ref of cssMapVariable.references) {
const node = ref.identifier;
const parent = node.parent;
if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'MemberExpression') {
if (!parent.computed && parent.property.type === 'Identifier') {
// Static access: styles.danger (not computed)
usedStyles.add(parent.property.name);
// Early exit if all styles are found
if (usedStyles.size === definedStyles.size) {
return;
}
} else {
// Dynamic access: styles[key], styles['danger'], etc. (computed)
// Immediately exit - no styles will be reported as unused
return;
}
}
}
// No dynamic access - report all unused styles
for (const [styleName, property] of definedStyles) {
if (!usedStyles.has(styleName)) {
this.report({
node: property.key,
messageId: 'unusedCssMapStyle',
data: {
styleName
}
});
}
}
}
findCssMapVariable() {
const callNode = this.cssMapCallNode;
const parent = callNode.parent;
if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'VariableDeclarator' && parent.id.type === 'Identifier') {
return findVariable({
identifier: parent.id,
sourceCode: getSourceCode(this.context)
});
}
return null;
}
run() {
this.checkForUnusedStyles();
}
}