77 lines
2.8 KiB
JavaScript
77 lines
2.8 KiB
JavaScript
import { JSXUtils } from "../jsx-utils.js";
|
|
export class JSXAttributeUtils {
|
|
types;
|
|
constructor(types) {
|
|
this.types = types;
|
|
}
|
|
hasAttribute(path, attributeName) {
|
|
return path.node.attributes.some((attr) => this.types.isJSXAttribute(attr) &&
|
|
JSXUtils.getAttributeName(attr) === attributeName);
|
|
}
|
|
addStringAttribute(path, attributeName, value) {
|
|
if (!this.hasAttribute(path, attributeName)) {
|
|
path.node.attributes.push(this.types.jsxAttribute(this.types.jsxIdentifier(attributeName), this.types.stringLiteral(value)));
|
|
}
|
|
}
|
|
addExpressionAttribute(path, attributeName, expression) {
|
|
if (!this.hasAttribute(path, attributeName)) {
|
|
path.node.attributes.push(this.types.jsxAttribute(this.types.jsxIdentifier(attributeName), this.types.jsxExpressionContainer(expression)));
|
|
}
|
|
}
|
|
}
|
|
export class StaticValueUtils {
|
|
types;
|
|
constructor(types) {
|
|
this.types = types;
|
|
}
|
|
isPrimitiveLiteral(path) {
|
|
return (path.isStringLiteral() ||
|
|
path.isNumericLiteral() ||
|
|
path.isBooleanLiteral() ||
|
|
path.isNullLiteral());
|
|
}
|
|
isStaticValue(path, visited = new Set()) {
|
|
if (this.isPrimitiveLiteral(path))
|
|
return true;
|
|
if (path.isIdentifier())
|
|
return this.isStaticIdentifier(path, visited);
|
|
if (path.isObjectExpression())
|
|
return this.isStaticObject(path, visited);
|
|
if (path.isArrayExpression())
|
|
return this.isStaticArrayExpression(path, visited);
|
|
return false;
|
|
}
|
|
isStaticIdentifier(path, visited = new Set()) {
|
|
const binding = path.scope.getBinding(path.node.name);
|
|
if (!binding)
|
|
return false;
|
|
if (binding.kind === "module")
|
|
return true;
|
|
if (binding.kind === "const" && binding.path.isVariableDeclarator()) {
|
|
const name = path.node.name;
|
|
if (visited.has(name))
|
|
return false;
|
|
visited.add(name);
|
|
const init = binding.path.get("init");
|
|
if (init.hasNode()) {
|
|
return this.isStaticValue(init, visited);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
isStaticObject(path, visited = new Set()) {
|
|
return path.get("properties").every((prop) => {
|
|
if (!prop.isObjectProperty())
|
|
return false;
|
|
return this.isStaticValue(prop.get("value"), visited);
|
|
});
|
|
}
|
|
isStaticArrayExpression(arrayExpression, visited = new Set()) {
|
|
return arrayExpression.get("elements").every((element) => {
|
|
if (!element.node || element.isSpreadElement())
|
|
return true;
|
|
return this.isStaticValue(element, visited);
|
|
});
|
|
}
|
|
}
|
|
//# sourceMappingURL=shared-utils.js.map
|