@navikt/aksel
Version:
Aksel command line interface. Handles css-imports, codemods and more
102 lines (101 loc) • 3.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = transformer;
const ast_1 = require("../../../utils/ast");
const lineterminator_1 = require("../../../utils/lineterminator");
const spacing_utils_1 = require("../spacing.utils");
function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
/**
* Migrate Primitives to `space` from `spacing`
*/
const primitives = [
"Box",
"Box.New",
"BoxNew",
"Hgrid",
"Stack",
"HStack",
"VStack",
"Bleed",
];
const affectedProps = [
"padding",
"paddingInline",
"paddingBlock",
"margin",
"marginInline",
"marginBlock",
"inset",
"top",
"right",
"bottom",
"left",
"gap",
];
for (const primitive of primitives) {
const name = (0, ast_1.findComponentImport)({ root, j, name: primitive });
if (!name) {
continue;
}
(0, ast_1.findJSXElement)({
root,
j,
name,
originalName: primitive,
}).forEach((path) => {
for (const prop of affectedProps) {
(0, ast_1.findProps)({ j, path, name: prop }).forEach((attr) => {
const attrValue = attr.value.value;
if (attrValue.type === "StringLiteral") {
/* padding="32" */
attrValue.value = convertSpacingToSpace(attrValue.value);
}
else if (attrValue.type === "JSXExpressionContainer") {
/* padding={{xs: "16", sm: "32"}} */
const expression = attrValue.expression;
if (expression.type === "ObjectExpression") {
/* xs, md, sm */
expression.properties.forEach((property) => {
if (property.type === "ObjectProperty") {
if (property.value.type === "StringLiteral") {
property.value.value = convertSpacingToSpace(property.value.value);
}
}
});
}
}
});
}
});
}
return root.toSource((0, lineterminator_1.getLineTerminator)(file.source));
}
/**
* Takes an old valid spacing-token and returns the new converted space-token
* oldValue: "8", "8 10", "8 auto", "auto auto", "full px"
* @returns "space-32", "space-32 space-40"
*/
function convertSpacingToSpace(oldValue) {
const spacingTokens = oldValue.split(" ");
const newSpacing = [];
for (const spacingToken of spacingTokens) {
if (spacingToken === "px") {
/* We replace "px" with new `space-1` */
newSpacing.push(`space-1`);
}
else if (["auto", "full", "px"].includes(spacingToken) ||
spacingToken.startsWith("space-")) {
newSpacing.push(spacingToken);
}
else if (!spacing_utils_1.legacySpacingTokenMap.get(spacingToken)) {
console.warn(`Possibly invalid spacing token found: ${spacingToken}\n`);
newSpacing.push(spacingToken);
}
else {
newSpacing.push(`space-${spacing_utils_1.legacySpacingTokenMap.get(spacingToken)}`);
}
}
return newSpacing.join(" ");
}