UNPKG

hbp-quickfire

Version:

A library of useful user-interface components built with React on top of React Bootstrap and MobX

158 lines (125 loc) 33.9 kB
var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();var _get = function get(object, property, receiver) {if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {var parent = Object.getPrototypeOf(object);if (parent === null) {return undefined;} else {return get(parent, property, receiver);}} else if ("value" in desc) {return desc.value;} else {var getter = desc.get;if (getter === undefined) {return undefined;}return getter.call(receiver);}};var _desc, _value, _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8;function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};}function _initDefineProp(target, property, descriptor, context) {if (!descriptor) return;Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 });}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {var desc = {};Object['ke' + 'ys'](descriptor).forEach(function (key) {desc[key] = descriptor[key];});desc.enumerable = !!desc.enumerable;desc.configurable = !!desc.configurable;if ('value' in desc || desc.initializer) {desc.writable = true;}desc = decorators.slice().reverse().reduce(function (desc, decorator) {return decorator(target, property, desc) || desc;}, desc);if (context && desc.initializer !== void 0) {desc.value = desc.initializer ? desc.initializer.call(context) : void 0;desc.initializer = undefined;}if (desc.initializer === void 0) {Object['define' + 'Property'](target, property, desc);desc = null;}return desc;}function _initializerWarningHelper(descriptor, context) {throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');} /* * Copyright (c) Human Brain Project * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { observable, action, toJS } from "mobx";import union from "lodash/union"; import DefaultField from "./DefaultField"; import FormStore from "../FormStore"; /** * @name Options * @memberof FormFields.NestedField * @param {string} label "" - The field label * @param {string} labelTooltip "" - The field label tooltip message * @param {string} labelTooltipPlacement "top" - The field label tooltip message position * @param {string} buttonLabel "Add an item" - The label used for adding an item to the repeatable fields * @param {string} type "Nested" * @param {number} min 1 - min of nested children the field can have * @param {number} max 1 - max of nested children the field can have * @param {object} fields {} - The nested fields definitions * @param {string} value [] - The value of the field * @param {array} defaultValue [] - The defaultValue of the field * @param {string} path "" - Field path * @param {string} topAddButton true - Whether or not to display the Add button before the fields * @param {string} bottomAddButton true - Whether or not to display the Add button after the fields * @param {boolean} emptyToNull false - Flag that determines if empty values are transformed to null in the value function of the formStore * @param {boolean} disabled false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues() * @param {boolean} readOnly false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues() * @param {boolean} readMode false - If true, displays the field as label and value without the actual form input */var NestedField = (_class = function (_DefaultField) {_inherits(NestedField, _DefaultField);_createClass(NestedField, null, [{ key: "properties", get: function get() { return union(_get(NestedField.__proto__ || Object.getPrototypeOf(NestedField), "properties", this), ["value", "defaultValue", "buttonLabel", "min", "max", "fields", "topAddButton", "bottomAddButton"]); } }]); function NestedField(fieldData, store, path) {_classCallCheck(this, NestedField);var _this = _possibleConstructorReturn(this, (NestedField.__proto__ || Object.getPrototypeOf(NestedField)).call(this, fieldData, store, path));_initDefineProp(_this, "value", _descriptor, _this);_initDefineProp(_this, "defaultValue", _descriptor2, _this);_initDefineProp(_this, "buttonLabel", _descriptor3, _this);_initDefineProp(_this, "min", _descriptor4, _this);_initDefineProp(_this, "max", _descriptor5, _this);_initDefineProp(_this, "fields", _descriptor6, _this);_initDefineProp(_this, "topAddButton", _descriptor7, _this);_initDefineProp(_this, "bottomAddButton", _descriptor8, _this);_this.__emptyValue = function () {return [];}; _this.injectValue(_this.value);return _this; }_createClass(NestedField, [{ key: "injectValue", value: function injectValue( value) {var _this2 = this; if (value !== undefined) { this.registerProvidedValue(value, true); } this.value = this.__emptyValue(); var providedValue = this.getProvidedValue(); providedValue.forEach(function (value) { if (!value || _this2.value.length >= _this2.max) { return; } _this2.addInstance(); _this2.store.injectValues(value, true, _this2.value[_this2.value.length - 1]); }); while (this.min !== Infinity && this.value.length < this.min) { this.addInstance(); } } }, { key: "setPath", value: function setPath( path) {var _this3 = this; this.path = path; this.value.map(function (fields, index) { _this3.store.remapPaths(fields, _this3.path + FormStore.getPathNodeSeparator() + index); }); } }, { key: "getValue", value: function getValue( applyMapping) {var _this4 = this; var value = []; this.value.forEach(function (subfields) { value.push(_this4.store.getValues(subfields, applyMapping)); }); return applyMapping ? this.mapReturnValue(value) : value; } }, { key: "addInstance", /** * add a new instance to a nested field * @memberof FormFields.NestedField */value: function addInstance() { var instance = toJS(this.fields); this.store.mapFields(instance, this.path + FormStore.getPathNodeSeparator() + this.value.length); this.value.push(instance); } }, { key: "duplicateInstance", /** * duplicates a nested instance at a given index * @param {integer} index the instance to duplicate index * @memberof FormFields.NestedField */value: function duplicateInstance( index) { var instance = toJS(this.fields); this.store.mapFields(instance, this.path + FormStore.getPathNodeSeparator() + (index + 1)); this.value.splice(index + 1, 0, instance); this.store.injectValues(this.store.getValues(this.value[index], false), true, this.path + FormStore.getPathNodeSeparator() + (index + 1)); this.setPath(this.path); } }, { key: "moveInstance", /** * move a nested instance at a given index to a new given index * @param {integer} index the instance to move * @param {integer} newIndex the index that instance will have * @memberof FormFields.NestedField */value: function moveInstance( index, newIndex) { if (newIndex < index) { var removedInstance = this.value.splice(index, 1); this.value.splice(newIndex, 0, removedInstance[0]); } else if (newIndex > index) { this.value.splice(newIndex + 1, 0, this.value[index]); this.value.splice(index, 1); } this.setPath(this.path); } }, { key: "removeInstance", /** * removes a nested instance at a given index * @param {integer} index the instance to remove index * @memberof FormFields.NestedField */value: function removeInstance( index) { this.value.splice(index, 1); this.setPath(this.path); } }, { key: "validate", value: function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {var validateChildren = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;var children, success, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, child, fieldKey, fieldStatus;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:if ( validateChildren) {_context.next = 2;break;}return _context.abrupt("return", true);case 2: children = this.value; success = true;_iteratorNormalCompletion = true;_didIteratorError = false;_iteratorError = undefined;_context.prev = 7;_iterator = children[Symbol.iterator]();case 9:if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {_context.next = 24;break;}child = _step.value;_context.t0 = regeneratorRuntime.keys( child);case 12:if ((_context.t1 = _context.t0()).done) {_context.next = 21;break;}fieldKey = _context.t1.value; fieldStatus = void 0;_context.next = 17;return ( child[fieldKey].validate(validateChildren));case 17:fieldStatus = _context.sent; success = fieldStatus && success;_context.next = 12;break;case 21:_iteratorNormalCompletion = true;_context.next = 9;break;case 24:_context.next = 30;break;case 26:_context.prev = 26;_context.t2 = _context["catch"](7);_didIteratorError = true;_iteratorError = _context.t2;case 30:_context.prev = 30;_context.prev = 31;if (!_iteratorNormalCompletion && _iterator.return) {_iterator.return();}case 33:_context.prev = 33;if (!_didIteratorError) {_context.next = 36;break;}throw _iteratorError;case 36:return _context.finish(33);case 37:return _context.finish(30);case 38:return _context.abrupt("return", success);case 39:case "end":return _context.stop();}}}, _callee, this, [[7, 26, 30, 38], [31,, 33, 37]]);}));function validate() {return _ref.apply(this, arguments);}return validate;}() }]);return NestedField;}(DefaultField), (_descriptor = _applyDecoratedDescriptor(_class.prototype, "value", [observable], { enumerable: true, initializer: function initializer() {return [];} }), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, "defaultValue", [observable], { enumerable: true, initializer: function initializer() {return [];} }), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, "buttonLabel", [observable], { enumerable: true, initializer: function initializer() {return "Add an item";} }), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, "min", [observable], { enumerable: true, initializer: function initializer() {return 1;} }), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, "max", [observable], { enumerable: true, initializer: function initializer() {return 1;} }), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, "fields", [observable], { enumerable: true, initializer: function initializer() {return {};} }), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, "topAddButton", [observable], { enumerable: true, initializer: function initializer() {return true;} }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "bottomAddButton", [observable], { enumerable: true, initializer: function initializer() {return true;} }), _applyDecoratedDescriptor(_class.prototype, "injectValue", [action], Object.getOwnPropertyDescriptor(_class.prototype, "injectValue"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "addInstance", [action], Object.getOwnPropertyDescriptor(_class.prototype, "addInstance"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "duplicateInstance", [action], Object.getOwnPropertyDescriptor(_class.prototype, "duplicateInstance"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "moveInstance", [action], Object.getOwnPropertyDescriptor(_class.prototype, "moveInstance"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "removeInstance", [action], Object.getOwnPropertyDescriptor(_class.prototype, "removeInstance"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "validate", [action], Object.getOwnPropertyDescriptor(_class.prototype, "validate"), _class.prototype)), _class);export { NestedField as default };