in packages/codegen-ui-react/lib/react-studio-template-renderer.ts [352:402]
private buildVariantPropNode(component: StudioComponent): TypeNode | undefined {
if (!isStudioComponentWithVariants(component)) {
return undefined;
}
const variantValues = component.variants.map((variant) => variant.variantValues);
const allKeys = [...new Set(variantValues.flatMap((variantValue) => Object.keys(variantValue)))];
const requiredKeys = allKeys
.filter((key) => variantValues.every((variantValue) => Object.keys(variantValue).includes(key)))
.sort();
const optionalKeys = [...allKeys].filter((key) => !requiredKeys.includes(key)).sort();
const requiredProperties = requiredKeys.map((key) => {
const variantOptions = [
...new Set(
variantValues
.map((variantValue) => variantValue[key])
.filter((variantOption) => variantOption !== undefined && variantOption !== null),
),
].sort();
const valueTypeNodes = variantOptions.map((variantOption) =>
factory.createLiteralTypeNode(factory.createStringLiteral(variantOption)),
);
return factory.createPropertySignature(
undefined,
factory.createIdentifier(key),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createUnionTypeNode(valueTypeNodes),
);
});
const optionalProperties = optionalKeys.map((key) => {
const variantOptions = [
...new Set(
variantValues
.map((variantValue) => variantValue[key])
.filter((variantOption) => variantOption !== undefined && variantOption !== null),
),
].sort();
const valueTypeNodes = variantOptions.map((variantOption) =>
factory.createLiteralTypeNode(factory.createStringLiteral(variantOption)),
);
return factory.createPropertySignature(
undefined,
factory.createIdentifier(key),
factory.createToken(ts.SyntaxKind.QuestionToken),
factory.createUnionTypeNode(valueTypeNodes),
);
});
return factory.createTypeLiteralNode([...requiredProperties, ...optionalProperties]);
}