@builder.io/mitosis
Version:
Write components once, run everywhere. Compiles to Vue, React, Solid, and Liquid. Import code from Figma and Builder.io
77 lines (76 loc) • 3.46 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStoreCode = void 0;
const core_1 = require("@babel/core");
const function_1 = require("fp-ts/lib/function");
const babel_transform_1 = require("../../../helpers/babel-transform");
const capitalize_1 = require("../../../helpers/capitalize");
const patterns_1 = require("../../../helpers/patterns");
const helpers_1 = require("./helpers");
const collectUsedStateAndPropsInFunction = (fnValue) => {
const stateUsed = new Set();
const propsUsed = new Set();
(0, babel_transform_1.babelTransformExpression)(fnValue, {
MemberExpression(path) {
const { node } = path;
if (core_1.types.isIdentifier(node.object)) {
if (core_1.types.isIdentifier(node.property)) {
if (node.object.name === 'state') {
stateUsed.add(`state.${node.property.name}`);
}
else if (node.object.name === 'props') {
propsUsed.add(`props.${node.property.name}`);
}
}
}
},
});
return { stateUsed, propsUsed };
};
const getStoreCode = ({ json: component, options, state, }) => {
const mapValue = (0, helpers_1.updateStateCode)({ options, component });
const stateUpdater = ([key, stateVal]) => {
if (!stateVal) {
return '';
}
const getCreateStoreStr = (initialValue) => `const [${key}, ${(0, helpers_1.getStateSetterName)(key)}] = createStore(${initialValue})`;
const getDefaultCase = () => (0, function_1.pipe)(value, mapValue, getCreateStoreStr);
const value = stateVal.code;
const type = stateVal.type;
if (typeof value === 'string') {
switch (type) {
case 'getter':
const getterValueAsFunction = (0, patterns_1.replaceGetterWithFunction)(value);
const { stateUsed, propsUsed } = collectUsedStateAndPropsInFunction(getterValueAsFunction);
const fnValueWithMappedRefs = mapValue(getterValueAsFunction);
const FUNCTION_NAME = `update${(0, capitalize_1.capitalize)(key)}`;
const deps = [
...Array.from(stateUsed).map((0, helpers_1.updateStateCode)({
options,
component,
// there are no setters in deps
updateSetters: false,
})),
...Array.from(propsUsed),
].join(', ');
return `
const ${FUNCTION_NAME} = ${fnValueWithMappedRefs}
${getCreateStoreStr(`${FUNCTION_NAME}()`)}
createEffect(on(() => [${deps}], () => ${(0, helpers_1.getStateSetterName)(key)}(reconcile(${FUNCTION_NAME}()))))
`;
case 'function':
return mapValue(value);
case 'method':
return (0, function_1.pipe)(value, patterns_1.prefixWithFunction, mapValue);
default:
return getDefaultCase();
}
}
else {
return getDefaultCase();
}
};
return Object.entries(state).map(stateUpdater).join(LINE_ITEM_DELIMITER);
};
exports.getStoreCode = getStoreCode;
const LINE_ITEM_DELIMITER = '\n\n\n';
;