@react-awesome-query-builder/core
Version:
User-friendly query builder for React. Core
301 lines (300 loc) • 12.7 kB
JavaScript
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import * as Utils from "../../utils";
import { compareToSign } from "../../export/spel";
var iterateFuncs = Utils.ConfigUtils.iterateFuncs;
var logger = Utils.OtherUtils.logger;
var isFuncableProperty = function isFuncableProperty(p) {
return ["length"].includes(p);
};
export var manuallyImportedOps = ["between", "not_between", "is_empty", "is_not_empty", "is_null", "is_not_null", "some", "all", "none"];
export var unsupportedOps = ["proximity"];
export var buildConv = function buildConv(config) {
var operators = {};
var _loop = function _loop(opKey) {
var opConfig = config.operators[opKey];
// const isGroupOp = config.settings.groupOperators?.includes(opKey);
var spelOps = opConfig.spelOps ? opConfig.spelOps : opConfig.spelOp ? [opConfig.spelOp] : undefined;
if (spelOps) {
// examples of 2+: "==", "eq", ".contains", "matches" (can be used for starts_with, ends_with)
spelOps.forEach(function (spelOp) {
var opk = spelOp; // + "/" + getOpCardinality(opConfig);
if (!operators[opk]) operators[opk] = [];
operators[opk].push(opKey);
});
} else {
var _config$operators;
var revOpConfig = (_config$operators = config.operators) === null || _config$operators === void 0 ? void 0 : _config$operators[opConfig.reversedOp];
var canUseRev = (revOpConfig === null || revOpConfig === void 0 ? void 0 : revOpConfig.spelOp) || (revOpConfig === null || revOpConfig === void 0 ? void 0 : revOpConfig.spelOps);
var canIgnore = canUseRev || manuallyImportedOps.includes(opKey) || manuallyImportedOps.includes(opConfig.reversedOp) || unsupportedOps.includes(opKey);
if (!canIgnore) {
logger.warn("[spel] No spelOp for operator ".concat(opKey));
}
}
};
for (var opKey in config.operators) {
_loop(opKey);
}
var conjunctions = {};
for (var conjKey in config.conjunctions) {
var conjunctionDefinition = config.conjunctions[conjKey];
var ck = conjunctionDefinition.spelConj || conjKey.toLowerCase();
conjunctions[ck] = conjKey;
}
var funcs = {};
var _iterator = _createForOfIteratorHelper(iterateFuncs(config)),
_step;
try {
var _loop3 = function _loop3() {
var _step$value = _slicedToArray(_step.value, 2),
funcPath = _step$value[0],
funcConfig = _step$value[1];
var fks = [];
var spelFunc = funcConfig.spelFunc;
if (typeof spelFunc === "string") {
var optionalArgs = Object.keys(funcConfig.args || {}).reverse().filter(function (argKey) {
return !!funcConfig.args[argKey].isOptional || funcConfig.args[argKey].defaultValue != undefined;
});
var funcSignMain = spelFunc
// Tip: convert "?." to "." to support safe navigation operator (issue #1010)
.replace(/\?\./g, ".").replace(/\${(\w+)}/g, function (_, _k) {
return "?";
});
var funcSignsOptional = optionalArgs.reduce(function (acc, argKey) {
return [].concat(_toConsumableArray(acc), [[argKey].concat(_toConsumableArray(acc[acc.length - 1] || []))]);
}, []).map(function (optionalArgKeys) {
return spelFunc.replace(/(?:, )?\${(\w+)}/g, function (found, a) {
return optionalArgKeys.includes(a) ? "" : found;
}).replace(/\?\./g, ".").replace(/\${(\w+)}/g, function (_, _k) {
return "?";
});
});
fks = [funcSignMain].concat(_toConsumableArray(funcSignsOptional));
}
var _iterator3 = _createForOfIteratorHelper(fks),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var _fk = _step3.value;
if (!funcs[_fk]) funcs[_fk] = [];
funcs[_fk].push(funcPath);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_loop3();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var valueFuncs = {};
for (var w in config.widgets) {
var widgetDef = config.widgets[w];
var spelImportFuncs = widgetDef.spelImportFuncs;
if (spelImportFuncs) {
var _iterator2 = _createForOfIteratorHelper(spelImportFuncs),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var fk = _step2.value;
if (typeof fk === "string") {
var fs = fk.replace(/\?\./g, ".").replace(/\${(\w+)}/g, function (_, k) {
return "?";
});
var argsOrder = _toConsumableArray(fk.matchAll(/\${(\w+)}/g)).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
_ = _ref2[0],
k = _ref2[1];
return k;
});
if (!valueFuncs[fs]) valueFuncs[fs] = [];
valueFuncs[fs].push({
w: w,
argsOrder: argsOrder
});
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
}
var opFuncs = {};
var _loop2 = function _loop2(op) {
var opDef = config.operators[op];
var spelOps = opDef.spelOps ? opDef.spelOps : opDef.spelOp ? [opDef.spelOp] : undefined;
spelOps === null || spelOps === void 0 || spelOps.forEach(function (spelOp) {
if (spelOp !== null && spelOp !== void 0 && spelOp.includes("${0}")) {
var _fs = spelOp.replace(/\?\./g, ".").replace(/\${(\w+)}/g, function (_, k) {
return "?";
});
var _argsOrder = _toConsumableArray(spelOp.matchAll(/\${(\w+)}/g)).map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
_ = _ref4[0],
k = _ref4[1];
return k;
});
if (!opFuncs[_fs]) opFuncs[_fs] = [];
opFuncs[_fs].push({
op: op,
argsOrder: _argsOrder
});
}
});
};
for (var op in config.operators) {
_loop2(op);
}
// Special .compareTo()
var compareToSS = compareToSign.replace(/\?\./g, ".").replace(/\${(\w+)}/g, function (_, k) {
return "?";
});
opFuncs[compareToSS] = [{
op: "!compare",
argsOrder: ["0", "1"]
}];
return {
operators: operators,
conjunctions: conjunctions,
funcs: funcs,
valueFuncs: valueFuncs,
opFuncs: opFuncs
};
};
export var buildFuncSignatures = function buildFuncSignatures(spel) {
// branches
var brns = [{
s: "",
params: [],
objs: []
}];
_buildFuncSignatures6(spel, brns);
return brns.map(function (_ref5) {
var s = _ref5.s,
params = _ref5.params;
return {
s: s,
params: params
};
}).reverse().filter(function (_ref6) {
var s = _ref6.s;
return s !== "" && s !== "?";
});
};
// a.toLower().toUpper()
// ->
// ?.toLower().toUpper()
// ?.toUpper()
var _buildFuncSignatures6 = function _buildFuncSignatures(spel, brns) {
var params = [],
s = "";
var type = spel.type,
methodName = spel.methodName,
val = spel.val,
obj = spel.obj,
args = spel.args,
isVar = spel.isVar,
cls = spel.cls,
children = spel.children;
var lastChild = children === null || children === void 0 ? void 0 : children[children.length - 1];
var currBrn = brns[brns.length - 1];
if (type === "!func") {
// T(DateTimeFormat).forPattern(?).parseDateTime(?) -- ok
// T(LocalDateTime).parse(?, T(DateTimeFormatter).ofPattern(?)) -- will not work
var o = obj;
while (o) {
var _currBrn$params;
var _buildFuncSignatures2 = _buildFuncSignatures6(_objectSpread(_objectSpread({}, o), {}, {
obj: null
}), [{}]),
_buildFuncSignatures3 = _slicedToArray(_buildFuncSignatures2, 2),
s1 = _buildFuncSignatures3[0],
params1 = _buildFuncSignatures3[1];
if (s1 !== "?") {
// start new branch
var newBrn = {
s: currBrn.s,
params: _toConsumableArray(currBrn.params),
objs: _toConsumableArray(currBrn.objs)
};
// finish old branch
currBrn.objs.unshift("?");
currBrn.params.unshift(o);
// switch
brns.push(newBrn);
currBrn = brns[brns.length - 1];
}
// step
currBrn.objs.unshift(s1);
(_currBrn$params = currBrn.params).unshift.apply(_currBrn$params, _toConsumableArray(params1));
o = o.type === "!func" ? o.obj : null;
}
var _iterator4 = _createForOfIteratorHelper(brns),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _brn$objs;
var brn = _step4.value;
params = [].concat(_toConsumableArray((brn === null || brn === void 0 ? void 0 : brn.params) || []), _toConsumableArray(args || []));
s = "";
if (brn !== null && brn !== void 0 && (_brn$objs = brn.objs) !== null && _brn$objs !== void 0 && _brn$objs.length) s += brn.objs.join(".") + ".";
s += (isVar ? "#" : "") + methodName;
s += "(" + (args || []).map(function (_) {
return "?";
}).join(", ") + ")";
brn.s = s;
brn.params = params;
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
} else if (type === "!new") {
// new java.text.SimpleDateFormat('HH:mm:ss').parse('...')
params = args || [];
s = "new ".concat(cls.join("."), "(").concat(params.map(function (_) {
return "?";
}).join(", "), ")");
} else if (type === "!type") {
// T(java.time.LocalTime).parse('...')
s = "T(".concat(cls.join("."), ")");
} else if (type === "compound" && lastChild.type === "property" && isFuncableProperty(lastChild.val)) {
// {1,2}.length -- ok
// 'Hello World'.bytes.length -- will not work
s = children.map(function (c) {
var _params;
if (c === lastChild) return c.val;
var _buildFuncSignatures4 = _buildFuncSignatures6(_objectSpread(_objectSpread({}, c), {}, {
obj: null
}), [{}]),
_buildFuncSignatures5 = _slicedToArray(_buildFuncSignatures4, 2),
s1 = _buildFuncSignatures5[0],
params1 = _buildFuncSignatures5[1];
(_params = params).push.apply(_params, _toConsumableArray(params1));
return s1;
}).join(".");
} else {
params = [spel];
s = "?";
}
if (currBrn) {
currBrn.s = s;
currBrn.params = params;
}
return [s, params];
};