hbp-quickfire
Version:
A library of useful user-interface components built with React on top of React Bootstrap and MobX
312 lines (184 loc) • 41.5 kB
JavaScript
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, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13, _descriptor14, _descriptor15, _descriptor16, _descriptor17, _descriptor18, _descriptor19;function _defineProperty(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 _toConsumableArray(arr) {if (Array.isArray(arr)) {for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {arr2[i] = arr[i];}return arr2;} else {return Array.from(arr);}}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, toJS, action, computed } from "mobx";import isString from "lodash/isString";import isNumber from "lodash/isNumber";import find from "lodash/find";import union from "lodash/union";import difference from "lodash/difference";import uniq from "lodash/uniq";
import DefaultField from "./DefaultField";
import optionsStore from "../OptionsStore";
/**
* @memberof FormFields.TreeSelectField
* @name Options
* @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} type "TreeSelect"
* @param {array} value [] - The current value of the field
* @param {array} defaultValue [] - The defaultValue of the field
* @param {array} data {} - The tree structure to select from, must be an object with eventually an array of children
* @param {array} dataUrl null - url to fetch the tree structure from
* @param {string} cacheDataUrl false - whether to cache dataUrl fetching response
* @param {string} path "" - Field path
* @param {string | array} mappingValue "value" - The name(s) of the node object field(s) related to the node value, used to match passed in values to actual tree nodes
* @param {string} mappingLabel "label" - the name of the node object field related to the node label
* @param {string} mappingChildren "children" - the name of the node object field related to the node children
* @param {string | array} mappingReturn null - the property/properties of the option object used to return the value(s) - null will return the whole object
* @param {boolean} returnSingle boolean - wether or not to return the first value or an array of values
* @param {number} max Infinity - Maximum values that the field can have
* @param {boolean} selectOnlyLeaf false - If enabled, only leaves can be selected and not the intermediary nodes
* @param {boolean} expandToSelectedNodes false - If enabled, tree selection modal will recursively expand to all the already selected values
* @param {array} defaultExpanded [] - an array of arrays describing a path of nodes expanded by default (tested on node labels, path parts are considered as RegExp)
* @param {boolean} showOnlySearchedNodes false - Flag that determines if nodes that doesn't match the text search should be hidden
* @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
* @param {array} groupByNodes [] - If provided, will display selected values grouped by the provided node matches
* @param {integer} groupByLevel null - If provided, will display selected values grouped by level
* @param {string} otherGroupLabel "Other values" - Label used for the group that contains values that doesn't fit into a group
*/var
TreeSelectField = (_class = function (_DefaultField) {_inherits(TreeSelectField, _DefaultField);_createClass(TreeSelectField, null, [{ key: "properties", get: function get()
{
return union(_get(TreeSelectField.__proto__ || Object.getPrototypeOf(TreeSelectField), "properties", this), [
"value", "defaultValue", "data", "dataUrl", "cacheDataUrl", "mappingValue", "mappingLabel", "mappingChildren",
"mappingReturn", "returnSingle", "max", "selectOnlyLeaf", "expandToSelectedNodes", "defaultExpanded",
"showOnlySearchedNodes", "valueLabelTransform", "groupByNodes", "groupByLevel", "otherGroupLabel"]);
} }]);
function TreeSelectField(fieldData, store, path) {_classCallCheck(this, TreeSelectField);
//Try to checked if cached options already exist
var _this = _possibleConstructorReturn(this, (TreeSelectField.__proto__ || Object.getPrototypeOf(TreeSelectField)).call(this, fieldData, store, path));_initDefineProp(_this, "value", _descriptor, _this);_initDefineProp(_this, "defaultValue", _descriptor2, _this);_initDefineProp(_this, "data", _descriptor3, _this);_initDefineProp(_this, "dataUrl", _descriptor4, _this);_initDefineProp(_this, "cacheDataUrl", _descriptor5, _this);_initDefineProp(_this, "mappingValue", _descriptor6, _this);_initDefineProp(_this, "mappingLabel", _descriptor7, _this);_initDefineProp(_this, "mappingChildren", _descriptor8, _this);_initDefineProp(_this, "mappingReturn", _descriptor9, _this);_initDefineProp(_this, "returnSingle", _descriptor10, _this);_initDefineProp(_this, "max", _descriptor11, _this);_initDefineProp(_this, "selectOnlyLeaf", _descriptor12, _this);_initDefineProp(_this, "expandToSelectedNodes", _descriptor13, _this);_initDefineProp(_this, "defaultExpanded", _descriptor14, _this);_initDefineProp(_this, "showOnlySearchedNodes", _descriptor15, _this);_initDefineProp(_this, "valueLabelTransform", _descriptor16, _this);_initDefineProp(_this, "groupByNodes", _descriptor17, _this);_initDefineProp(_this, "groupByLevel", _descriptor18, _this);_initDefineProp(_this, "otherGroupLabel", _descriptor19, _this);_this.nodeParents = new Map();_this.__emptyValue = function () {return [];};if (_this.cacheDataUrl && _this.dataUrl) {
var data = optionsStore.getOptions(_this.dataUrl);
if (data !== undefined) {
_this.dataUrl = null;
_this.data = data;
}
}
//If no data are provided, we make it an empty object
//Cannot set this as default value for property since it's an observable
//We need mobx to consider making the whole provided object to an observable
//That's why it's initialized no null
if (!_this.data) {
_this.data = {};
} else {
_this.updateNodeParentsMap();
}
_this.injectValue(_this.value);return _this;
}_createClass(TreeSelectField, [{ key: "getValue", value: function getValue(
applyMapping) {
var result = this.value.map(function (node) {
var nodeClone = toJS(node);
if (nodeClone.children !== undefined) {
delete nodeClone.children;
}
return nodeClone;
});
return applyMapping ? this.mapReturnValue(result) : result;
} }, { key: "rfind",
//Looks for a match recursively, stops at the first match
value: function rfind(nodes, testCb) {var _this2 = this;
var foundNode = find(nodes, testCb);
if (!foundNode) {
find(nodes, function (node) {
if (node[_this2.mappingChildren] && node[_this2.mappingChildren].length) {
foundNode = _this2.rfind(node[_this2.mappingChildren], testCb, _this2.mappingChildren);
}
return !!foundNode;
});
}
return foundNode;
} }, { key: "rfindMatch", value: function rfindMatch(
nodes, valueToMatch) {var _this3 = this;
var match = void 0;
//Below are the tests to find matches in the tree structure for each provided value
//If the provided value is scalar then we check against the mappingValue property(ies) of each
//node (and stop at the first match). Each mappingValue property has to match the scalar value (edge case)
//If the provided value is an object then we check against the mappingValue property(ies) of each
//node (and stop at the first match). Each mappingValue property has to match its respective counterpart in the node object
if (isString(valueToMatch) || isNumber(valueToMatch)) {
match = this.rfind(nodes, function (node) {return (
isString(_this3.mappingValue) || isNumber(_this3.mappingValue) ?
node[_this3.mappingValue] === valueToMatch :
_this3.mappingValue.every(function (prop) {return node[prop] === valueToMatch;}));},
this.mappingChildren);
} else if (valueToMatch != null) {
match = this.rfind(nodes, function (node) {return (
isString(_this3.mappingValue) || isNumber(_this3.mappingValue) ?
node[_this3.mappingValue] === valueToMatch[_this3.mappingValue] :
_this3.mappingValue.every(function (prop) {return typeof node[prop] != "undefined" && typeof valueToMatch[prop] != "undefined" && node[prop] === valueToMatch[prop];}));} // Allow the prop to be null, if necessary
,
this.mappingChildren);
}
return match;
} }, { key: "findAllNodesAtLevel", value: function findAllNodesAtLevel(
level) {
var result = [];
var rseek = function rseek(nodes, currentLevel) {
if (level === currentLevel) {
result.push.apply(result, _toConsumableArray(nodes));
} else if (level > currentLevel) {
nodes.forEach(function (node) {
if (node.children && node.children.length) {
rseek(node.children, currentLevel + 1);
}
});
}
};
rseek([this.data], 0);
return result;
} }, { key: "transformedValueLabel", value: function transformedValueLabel(
node) {var _this4 = this;
if (this.valueLabelTransform.search) {
var label = this.getNodePathOf(node).map(function (parentNode) {return parentNode[_this4.mappingLabel];}).join(" > ");
return label.replace(new RegExp(this.valueLabelTransform.search, "gi"), this.valueLabelTransform.replace);
}
return node[this.mappingLabel];
} }, { key: "injectValue", value: function injectValue(
value) {var _this5 = this;
if (value !== undefined) {
this.registerProvidedValue(value, true);
}
this.value = this.__emptyValue();
var providedValue = this.getProvidedValue();
providedValue.forEach(function (value) {
if (!value || _this5.value.length >= _this5.max) {
return;
}
var match = _this5.rfindMatch([_this5.data], value);
if (match) {
_this5.addValue(match);
}
});
} }, { key: "updateData", value: function updateData(
data) {
this.data = data;
this.updateNodeParentsMap();
this.injectValue();
} }, { key: "updateNodeParentsMap", value: function updateNodeParentsMap()
{var _this6 = this;
this.nodeParents = new Map();
var mapNodesToParent = function mapNodesToParent(parentNode) {
if (parentNode.children) {
parentNode.children.forEach(function (childNode) {
_this6.nodeParents.set(childNode, parentNode);
mapNodesToParent(childNode);
});
}
};
mapNodesToParent(this.data);
} }, { key: "getNodeParentOf", value: function getNodeParentOf(
node) {
if (this.nodeParents.has(node)) {
return this.nodeParents.get(node);
} else {
return null;
}
} }, { key: "getNodePathOf", value: function getNodePathOf(
node) {
var path = [node];
var parentNode = node;
while ((parentNode = this.getNodeParentOf(parentNode)) !== null) {
path.unshift(parentNode);
}
return path;
} }, { key: "groupedValues", get: function get() {var _this7 = this;var result = new Map();var valuesInAGroup = [];var valuesPath = new Map();this.value.forEach(function (node) {valuesPath.set(node, _this7.getNodePathOf(node));});if (this.groupByLevel !== null) {this.findAllNodesAtLevel(this.groupByLevel).forEach(function (groupNode) {valuesPath.forEach(function (path, node) {if (path.indexOf(groupNode) !== -1) {if (!result.has(groupNode)) {result.set(groupNode, []);}if (result.get(groupNode).indexOf(node) === -1) {result.get(groupNode).push(node);}valuesInAGroup.push(node);}});});}if (this.groupByNodes) {this.groupByNodes.forEach(function (nodeValue) {var groupNode = _this7.rfindMatch([_this7.data], nodeValue);if (groupNode) {valuesPath.forEach(function (path, node) {if (path.indexOf(groupNode) !== -1) {if (!result.has(groupNode)) {result.set(groupNode, []);}if (result.get(groupNode).indexOf(node) === -1) {result.get(groupNode).push(node);}valuesInAGroup.push(node);}});}});}if (this.value.length > uniq(valuesInAGroup).length) {var otherGroup = _defineProperty({}, this.mappingLabel, this.otherGroupLabel);result.set(otherGroup, []);difference(this.value, valuesInAGroup).forEach(function (value) {result.get(otherGroup).push(value);});}return result;} }, { key: "groupLabels", get: function get() {var _this8 = this;var result = new Map();this.groupByNodes.forEach(function (nodeValue) {var match = _this8.rfindMatch([_this8.data], nodeValue);if (match) {result.set(match, nodeValue.groupLabel || match[_this8.mappingLabel]);}});return result;} }, { key: "displayValueAsGrouped", get: function get() {return !!this.groupByNodes.length || this.groupByLevel !== null;} }]);return TreeSelectField;}(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, "data", [observable], { enumerable: true, initializer: function initializer() {return null;} }), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, "dataUrl", [observable], { enumerable: true, initializer: function initializer() {return null;} }), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, "cacheDataUrl", [observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, "mappingValue", [observable], { enumerable: true, initializer: function initializer() {return "value";} }), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, "mappingLabel", [observable], { enumerable: true, initializer: function initializer() {return "label";} }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, "mappingChildren", [observable], { enumerable: true, initializer: function initializer() {return "children";} }), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, "mappingReturn", [observable], { enumerable: true, initializer: function initializer() {return null;} }), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, "returnSingle", [observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, "max", [observable], { enumerable: true, initializer: function initializer() {return Infinity;} }), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, "selectOnlyLeaf", [observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, "expandToSelectedNodes", [observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor14 = _applyDecoratedDescriptor(_class.prototype, "defaultExpanded", [observable], { enumerable: true, initializer: function initializer() {return [];} }), _descriptor15 = _applyDecoratedDescriptor(_class.prototype, "showOnlySearchedNodes", [observable], { enumerable: true, initializer: function initializer() {return false;} }), _descriptor16 = _applyDecoratedDescriptor(_class.prototype, "valueLabelTransform", [observable], { enumerable: true, initializer: function initializer() {return { search: "", replace: "" };} }), _descriptor17 = _applyDecoratedDescriptor(_class.prototype, "groupByNodes", [observable], { enumerable: true, initializer: function initializer() {return [];} }), _descriptor18 = _applyDecoratedDescriptor(_class.prototype, "groupByLevel", [observable], { enumerable: true, initializer: function initializer() {return null;} }), _descriptor19 = _applyDecoratedDescriptor(_class.prototype, "otherGroupLabel", [observable], { enumerable: true, initializer: function initializer() {return "Other values";} }), _applyDecoratedDescriptor(_class.prototype, "groupedValues", [computed], Object.getOwnPropertyDescriptor(_class.prototype, "groupedValues"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "groupLabels", [computed], Object.getOwnPropertyDescriptor(_class.prototype, "groupLabels"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "displayValueAsGrouped", [computed], Object.getOwnPropertyDescriptor(_class.prototype, "displayValueAsGrouped"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "injectValue", [action], Object.getOwnPropertyDescriptor(_class.prototype, "injectValue"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateData", [action], Object.getOwnPropertyDescriptor(_class.prototype, "updateData"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateNodeParentsMap", [action], Object.getOwnPropertyDescriptor(_class.prototype, "updateNodeParentsMap"), _class.prototype)), _class);export { TreeSelectField as default };