@talend/react-forms
Version:
React forms library based on json schema form.
101 lines (95 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _jsonLogicJs = _interopRequireDefault(require("json-logic-js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/* eslint-disable @typescript-eslint/no-use-before-define */
function lowercase(a) {
return a.toLowerCase();
}
function toNumber(a) {
if (typeof a === 'number') {
return a;
} else if (typeof a === 'string') {
return parseInt(a, 10);
}
throw new TypeError(`${a.toString()} is not a number`);
}
_jsonLogicJs.default.add_operation('lowercase', lowercase);
_jsonLogicJs.default.add_operation('toNumber', toNumber);
/**
* If in the path [] appears it will be populated
* with current key indices value.
*/
function replaceArrayNotationByIndexes(path, key) {
if (!path || !path.includes('[]')) {
return path;
}
return path.split(/\.|\[/).map((part, index) => {
if (part === ']') {
return key[index];
}
return part;
}).join('.');
}
/**
* For all "var" condition, populate generic indices ([]) from key indices.
*/
function resolveConditionVar(item, key) {
if (!item || typeof item !== 'object') {
return item;
} else if (item.var) {
if (item.var.includes('[]')) {
return {
...item,
var: replaceArrayNotationByIndexes(item.var, key)
};
}
return item;
} else if (Array.isArray(item)) {
return item.map(it => resolveArrayNotation(it, key));
}
return resolveArrayNotation(item, key);
}
/**
* Ensure generic indices ([]) are populated from the key.
* It is a recursive implementation to support any kind of condition.
*/
function resolveArrayNotation(condition, key) {
if (typeof condition !== 'object') {
return condition;
}
const acc = {};
Object.keys(condition).forEach(attribute => {
const value = condition[attribute];
if (Array.isArray(value)) {
acc[attribute] = value.map(it => resolveConditionVar(it, key));
} else {
acc[attribute] = resolveConditionVar(value, key);
}
return acc;
});
return acc;
}
/**
*
* @example {
* '===': [{ var: 'my.path.title' }, 'Hello world'],
* }
*
* @param properties source of the value provider to evaluate conditions.
* @param condition array of conditions to evaluate.
* @param key the widget schema key.
* @returns true if the conditions are met, false otherwise.
*/
function shouldRender(condition, properties, key) {
if (condition === undefined) {
return true;
}
const runtimeCondition = resolveArrayNotation(condition, key);
return _jsonLogicJs.default.apply(runtimeCondition, properties);
}
var _default = exports.default = shouldRender;
//# sourceMappingURL=condition.js.map