@builder.io/mitosis
Version:
Write components once, run everywhere. Compiles to Vue, React, Solid, and Liquid. Import code from Figma and Builder.io
60 lines (59 loc) • 2.63 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.processTargetBlocks = void 0;
const use_target_1 = require("../../parsers/jsx/hooks/use-target");
const bindings_1 = require("../bindings");
const process_code_1 = require("./process-code");
const getBlockForTarget = ({ target, targetBlock, }) => {
switch (target) {
default:
return targetBlock[target] || targetBlock['default'];
}
};
/**
* Processes `useTarget()` blocks for a given target.
*/
const processTargetBlocks = (target) => {
const plugin = (0, process_code_1.createCodeProcessorPlugin)((codeType, json, node) => (code, key) => {
var _a;
if (codeType === 'properties') {
const matches = code.includes(use_target_1.USE_TARGET_MAGIC_STRING);
const property = node === null || node === void 0 ? void 0 : node.properties[key];
if (!matches || !property)
return code;
node.bindings[key] = (0, bindings_1.createSingleBinding)({ code: `"${property}"` });
return () => {
delete node.properties[key];
};
}
const matches = code.match(use_target_1.USE_TARGET_MAGIC_REGEX);
if (!matches)
return code;
for (const m of matches) {
// get the captured ID of the target block
const targetId = (0, use_target_1.getIdFromMatch)(m);
if (!targetId)
continue;
// find the target block in the component, or the default target block
const targetBlock = (_a = json.targetBlocks) === null || _a === void 0 ? void 0 : _a[targetId];
if (!targetBlock) {
throw new Error(`Could not find \`useTarget()\` value in "${json.name}".`);
}
const block = getBlockForTarget({ target, targetBlock });
if (!block) {
if (targetBlock.settings.requiresDefault) {
throw new Error(`Could not find \`useTarget()\` value in "${json.name}" for target "${target}", and no default value was set.`);
}
else {
// if we don't need a default, then that means we allow for nothing to be injected, e.g. when we are in a function body.
code = code.replaceAll(m, '');
continue;
}
}
code = code.replaceAll(m, block.code);
}
return code;
}, { processProperties: true });
return () => ({ json: { pre: plugin } });
};
exports.processTargetBlocks = processTargetBlocks;
;