@kuma-ui/compiler
Version:
🐻 Kuma UI is a utility-first, zero-runtime CSS-in-JS library that offers an outstanding developer experience and optimized performance.
61 lines (59 loc) • 1.97 kB
JavaScript
// src/optimizer/optimize.ts
import {
defaultComponentTag
} from "@kuma-ui/core/components/componentList";
import {
Node,
SyntaxKind
} from "ts-morph";
import { isStyledProp, isPseudoProps } from "@kuma-ui/system";
var optimize = (componentName, jsxElement, as) => {
const isOptimizable = jsxElement.getAttributes().every((attrLike) => {
if (Node.isJsxSpreadAttribute(attrLike))
return false;
const attr = attrLike.asKindOrThrow(SyntaxKind.JsxAttribute);
if (hasDynamicProp(attr.getNameNode().getText().trim(), !!as))
return false;
return true;
});
if (!isOptimizable)
return;
const rawHTMLTag = (() => {
const safeAs = typeof as === "string" ? as.replace(/['"`]/g, "") : as;
const tag = defaultComponentTag[componentName];
if (safeAs) {
return safeAs;
} else {
if (typeof tag === "string")
return tag;
return "div";
}
})();
safeReplaceTagName(jsxElement, rawHTMLTag);
};
function hasDynamicProp(key, hasAs) {
return isStyledProp(key) || isPseudoProps(key) || key === "variant" || !hasAs && key === "as";
}
function safeReplaceTagName(jsxElement, newTagName) {
const originalComponent = jsxElement.getTagNameNode().getText();
try {
if (Node.isJsxOpeningElement(jsxElement)) {
const jsxElementParent = jsxElement.getParentIfKind(
SyntaxKind.JsxElement
);
if (jsxElementParent) {
jsxElementParent.getOpeningElement().getTagNameNode().replaceWithText(newTagName);
jsxElementParent.getClosingElement().getTagNameNode().replaceWithText(newTagName);
}
} else if (Node.isJsxSelfClosingElement(jsxElement)) {
jsxElement.getTagNameNode().replaceWithText(newTagName);
jsxElement.getFirstDescendantByKind(SyntaxKind.Identifier)?.replaceWithText(newTagName);
}
jsxElement.getAttribute("as")?.remove();
jsxElement.getAttribute("IS_KUMA_DEFAULT")?.remove();
} catch {
}
}
export {
optimize
};