@schema-render/core-react
Version:
Through a set of simple JSON Schema, efficiently build a set of forms.
603 lines (602 loc) • 25.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
makeOpenValidatorParams: function() {
return makeOpenValidatorParams;
},
validateFormItem: function() {
return validateFormItem;
},
validateRootSchema: function() {
return validateRootSchema;
}
});
var _constants = require("../constants");
var _tinyLodash = require("./tinyLodash");
var _base = require("./base");
var _checking = require("./checking");
var _misc = require("./misc");
var _renderer = require("./renderer");
var _schemaRulesValidator = require("./schemaRulesValidator");
var _statement = require("./statement");
var _traverseSchema = /*#__PURE__*/ _interop_require_default(require("./traverseSchema"));
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
function validateRootSchema(_) {
return _validateRootSchema.apply(this, arguments);
}
function _validateRootSchema() {
_validateRootSchema = _async_to_generator(function(param) {
var rootSchema, rootValue, disabled, readonly, locale, renderers, rendererStorage, validators, userCtx, items, errorList, warningList, emittingList;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
rootSchema = param.rootSchema, rootValue = param.rootValue, disabled = param.disabled, readonly = param.readonly, locale = param.locale, renderers = param.renderers, rendererStorage = param.rendererStorage, validators = param.validators, userCtx = param.userCtx;
items = [];
(0, _traverseSchema.default)(rootSchema, {
$$: {
enter: function(param) {
var schema = param.schema, path = param.path;
// 执行 hidden 语法
var shouldHidden = (0, _statement.performStatementWithPath)({
statement: schema.hidden,
rootValue: rootValue,
path: path,
userCtx: userCtx
});
if (shouldHidden) {
return;
}
var renderer = (0, _renderer.matchRenderer)(renderers, schema.renderType);
if (!renderer) {
return;
}
var handler = /*#__PURE__*/ function() {
var _ref = _async_to_generator(function() {
var value, validatorParams, _ref, status, message, extra, err;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
value = (0, _tinyLodash.get)(rootValue, path);
validatorParams = makeOpenValidatorParams({
schema: schema,
value: value,
path: path,
disabled: disabled,
readonly: readonly,
rootValue: rootValue,
locale: locale,
userCtx: userCtx
});
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
return [
4,
validateFormItem({
schema: schema,
rootValue: rootValue,
userCtx: userCtx,
path: path,
locale: locale,
value: value,
globalValidators: validators,
rendererValidator: renderer.validator,
rendererValidatorParams: validatorParams
})
];
case 2:
_ref = _state.sent(), status = _ref.status, message = _ref.message, extra = _ref.extra;
if (status !== _constants.EValidationStatus.success) {
return [
2,
{
path: path,
value: value,
status: status,
message: message,
extra: extra
}
];
}
return [
3,
4
];
case 3:
err = _state.sent();
return [
2,
{
path: path,
value: value,
status: _constants.EValidationStatus.error,
message: "[CatchError]: ".concat(err === null || err === void 0 ? void 0 : err.message)
}
];
case 4:
return [
2
];
}
});
});
return function handler() {
return _ref.apply(this, arguments);
};
}();
items.push(handler());
}
},
$$Object: {
enter: function(param) {
var traverse = param.traverse;
traverse();
}
}
}, {
clone: false
});
errorList = [];
warningList = [];
return [
4,
Promise.all(items).then(function(res) {
return res.filter(function(item) {
if ((item === null || item === void 0 ? void 0 : item.status) === _constants.EValidationStatus.error) {
// 错误列表
errorList.push(item);
} else if ((item === null || item === void 0 ? void 0 : item.status) === _constants.EValidationStatus.warning) {
// 警告列表
warningList.push(item);
}
// 过滤校验通过的返回值,即 undefined
return !!item;
});
})
];
case 1:
emittingList = _state.sent();
// 通知渲染器展示错误或警告信息
emittingList.forEach(function(param) {
var status = param.status, path = param.path, message = param.message, extra = param.extra;
var renderer = rendererStorage[(0, _misc.stringifyPath)(path)];
renderer === null || renderer === void 0 ? void 0 : renderer.setValidatorState({
status: status,
message: message,
extra: extra
});
});
return [
2,
{
hasError: !!errorList.length,
hasWarning: !!warningList.length,
errorList: errorList,
warningList: warningList
}
];
}
});
});
return _validateRootSchema.apply(this, arguments);
}
function validateFormItem(_) {
return _validateFormItem.apply(this, arguments);
}
function _validateFormItem() {
_validateFormItem = _async_to_generator(function(param) {
var schema, rootValue, userCtx, path, locale, value, globalValidators, rendererValidator, rendererValidatorParams, rules, commonValidateRulesParams, result, result1, fnResult, result2;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
schema = param.schema, rootValue = param.rootValue, userCtx = param.userCtx, path = param.path, locale = param.locale, value = param.value, globalValidators = param.globalValidators, rendererValidator = param.rendererValidator, rendererValidatorParams = param.rendererValidatorParams;
// 将 schema.required 添加到 rules 规则
rules = composeSchemaRules({
schema: schema,
rootValue: rootValue,
path: path,
locale: locale,
userCtx: userCtx
});
commonValidateRulesParams = {
value: value,
globalValidators: globalValidators,
globalValidatorParams: rendererValidatorParams,
locale: locale.validation
};
if (!(0, _schemaRulesValidator.isValidRules)(rules)) return [
3,
2
];
return [
4,
(0, _schemaRulesValidator.validateRules)(_object_spread_props(_object_spread({}, commonValidateRulesParams), {
rules: rules
}))
];
case 1:
result = _state.sent();
if (result.status !== _constants.EValidationStatus.success) {
return [
2,
result
];
}
_state.label = 2;
case 2:
if (!(0, _schemaRulesValidator.isValidRules)(rendererValidator)) return [
3,
4
];
return [
4,
(0, _schemaRulesValidator.validateRules)(_object_spread_props(_object_spread({}, commonValidateRulesParams), {
rules: rendererValidator
}))
];
case 3:
result1 = _state.sent();
return [
2,
result1
];
case 4:
if (!(0, _checking.isFunction)(rendererValidator)) return [
3,
8
];
return [
4,
rendererValidator(_object_spread_props(_object_spread({}, rendererValidatorParams), {
value: value
}))
];
case 5:
fnResult = _state.sent();
if (!(0, _schemaRulesValidator.isValidRules)(fnResult)) return [
3,
7
];
return [
4,
(0, _schemaRulesValidator.validateRules)(_object_spread_props(_object_spread({}, commonValidateRulesParams), {
rules: fnResult
}))
];
case 6:
result2 = _state.sent();
return [
2,
result2
];
case 7:
// 渲染器内置校验(返回值 SchemaRender 规则)
if ((0, _schemaRulesValidator.isValidFunctionResult)(fnResult)) {
return [
2,
{
status: fnResult.status,
message: fnResult.message,
extra: fnResult.extra
}
];
}
_state.label = 8;
case 8:
return [
2,
{
status: _constants.EValidationStatus.success
}
];
}
});
});
return _validateFormItem.apply(this, arguments);
}
/**
* 将 schema.required 添加到 rules 规则
*/ function composeSchemaRules(param) {
var schema = param.schema, rootValue = param.rootValue, path = param.path, locale = param.locale, userCtx = param.userCtx;
var rules = (0, _schemaRulesValidator.normalizeRules)(schema.rules);
var isRequired = (0, _statement.performStatementWithPath)({
statement: schema.required,
rootValue: rootValue,
path: path,
userCtx: userCtx
});
if (isRequired && !(0, _tinyLodash.find)(schema.rules, {
required: true
})) {
rules.unshift({
required: true,
message: (0, _base.templateCompiled)(locale.validation.required, {
label: schema.title
})
});
}
return rules;
}
/**
* 获取 Schema required 的值,由以下两个协议确定
* - schema.required 的值
* - schema.rules 内 required 的值
*/ function calcRequiredValue(param) {
var schema = param.schema, rootValue = param.rootValue, path = param.path, userCtx = param.userCtx;
var isRequired = (0, _statement.performStatementWithPath)({
statement: schema.required,
rootValue: rootValue,
path: path,
userCtx: userCtx
});
if (isRequired) {
return true;
}
if ((0, _tinyLodash.find)((0, _schemaRulesValidator.normalizeRules)(schema.rules), {
required: true
})) {
return true;
}
return false;
}
function makeOpenValidatorParams(param) {
var schema = param.schema, value = param.value, path = param.path, disabled = param.disabled, readonly = param.readonly, rootValue = param.rootValue, locale = param.locale, userCtx = param.userCtx;
// 优先使用全局禁用态、只读态
var innerDisabled = !!disabled;
var innerReadonly = !!readonly;
// 已禁用的状态下,不需要执行语句,提升性能
if (!innerDisabled) {
innerDisabled = (0, _statement.performStatementWithPath)({
statement: schema.disabled,
rootValue: rootValue,
path: path,
userCtx: userCtx
});
}
// 只读态处理
if (!innerReadonly) {
innerReadonly = (0, _statement.performStatementWithPath)({
statement: schema.readonly,
rootValue: rootValue,
path: path,
userCtx: userCtx
});
}
// 是否必填
var required = calcRequiredValue({
schema: schema,
path: path,
rootValue: rootValue,
userCtx: userCtx
});
return {
schema: schema,
value: value,
path: _to_consumable_array(path),
sPath: (0, _misc.stringifyPath)(path),
required: required,
disabled: innerDisabled,
readonly: innerReadonly,
rootValue: rootValue,
locale: locale,
userCtx: userCtx
};
}