UNPKG

hbp-quickfire

Version:

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

369 lines (254 loc) 26.2 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 _dec, _dec2, _class;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 _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;} /* * 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 React from "react"; import { inject, observer } from "mobx-react";import FormGroup from "react-bootstrap/lib/FormGroup";import Button from "react-bootstrap/lib/Button";import Glyphicon from "react-bootstrap/lib/Glyphicon";import Modal from "react-bootstrap/lib/Modal";import Alert from "react-bootstrap/lib/Alert";import isFunction from "lodash/isFunction"; import injectStyles from "react-jss"; import FieldLabel from "./FieldLabel"; import Tree from "./Tree"; var styles = { values: { display: "block", height: "auto", minHeight: "36px", paddingBottom: "3px", paddingRight: "36px", "& .btn.value-tag": { marginRight: "3px", marginBottom: "3px" }, "& input": { border: "none", outline: "none", width: "200px", maxWidth: "30%", marginBottom: "3px" }, "& :disabled": { pointerEvents: "none" }, "& [readonly] .quickfire-remove": { pointerEvents: "none" }, "&[readonly] .quickfire-user-input, &[disabled] .quickfire-user-input": { display: "none" } }, valueDisplay: { display: "inline-block", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", verticalAlign: "bottom" }, valueGroup: { marginBottom: "12px", "&:last-of-type": { marginBottom: "4px" }, "& legend": { fontSize: "1.05em", fontWeight: "bold", marginBottom: "8px" } }, remove: { fontSize: "0.8em", opacity: 0.5, marginLeft: "3px", "&:hover": { opacity: 1 } }, openButton: { position: "absolute", top: 0, right: 0, height: "100%", margin: "0", borderTopLeftRadius: 0, borderBottomLeftRadius: 0, borderRight: "none", borderTop: "none", borderBottom: "none" }, readMode: { "& .quickfire-label:after": { content: "':\\00a0'" }, "& .quickfire-readmode-item:not(:last-child):after": { content: "',\\00a0'" } } }; /** * Form component allowing to select multiple values from a tree structure * @class TreeSelectField * @memberof FormFields * @namespace TreeSelectField */var TreeSelectField = (_dec = inject("formStore"), _dec2 = injectStyles(styles), _dec(_class = _dec2(_class = observer(_class = function (_React$Component) {_inherits(TreeSelectField, _React$Component); function TreeSelectField(props) {_classCallCheck(this, TreeSelectField);var _this = _possibleConstructorReturn(this, (TreeSelectField.__proto__ || Object.getPrototypeOf(TreeSelectField)).call(this, props));_this. triggerOnLoad = function () { if (_this.hiddenInputRef && _this.hiddenInputRef.parentNode) { var event = new Event("load", { bubbles: true }); _this.hiddenInputRef.dispatchEvent(event); } };_this. triggerOnChange = function () { Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set. call(_this.hiddenInputRef, JSON.stringify(_this.props.field.getValue(false))); var event = new Event("input", { bubbles: true }); _this.hiddenInputRef.dispatchEvent(event); };_this. handleFocus = function () { var field = _this.props.field; if (field.disabled || field.readOnly) { return; } if (field.value.length < field.max || field.max === 1) { _this.setState({ showTree: true }); } };_this. handleHideModal = function () { _this.setState({ showTree: false }); };_this. handleSelect = function (node) { var field = _this.props.field; if (field.disabled || field.readOnly) { return; } if (field.value.length < field.max) { if (field.value.indexOf(node) !== -1) { _this.beforeRemoveValue(node); } else { _this.beforeAddValue(node); } _this.triggerOnChange(); } else if (field.max === 1) { _this.beforeSetValue(node); _this.triggerOnChange(); } if (field.value.length >= field.max) { _this.handleHideModal(); } };_this.state = { showTree: false };_this.initField();return _this;}_createClass(TreeSelectField, [{ key: "initField", value: function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {var _props, field, formStore, dataUrl, cacheDataUrl;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_props = this.props, field = _props.field, formStore = _props.formStore;dataUrl = field.dataUrl, cacheDataUrl = field.cacheDataUrl;if (!dataUrl) {_context.next = 9;break;}_context.t0 = field;_context.next = 6;return formStore.resolveURL(dataUrl, cacheDataUrl);case 6:_context.t1 = _context.sent;_context.t0.updateData.call(_context.t0, _context.t1);this.triggerOnLoad();case 9:case "end":return _context.stop();}}}, _callee, this);}));function initField() {return _ref.apply(this, arguments);}return initField;}() //The only way to trigger an onChange event in React is to do the following //Basically changing the field value, bypassing the react setter and dispatching an "input" // event on a proper html input node //See for example the discussion here : https://stackoverflow.com/a/46012210/9429503 }, { key: "handleRemove", value: function handleRemove(value, e) {var field = this.props.field;e.stopPropagation();if (field.disabled || field.readOnly) {return;}this.beforeRemoveValue(value);this.triggerOnChange();} }, { key: "handleRemoveBackspace", value: function handleRemoveBackspace(value, e) {var field = this.props.field;if (field.disabled || field.readOnly) {return;} //User pressed "Backspace" while focus on a value if (e.keyCode === 8) {e.preventDefault();this.beforeRemoveValue(value);this.triggerOnChange();}} }, { key: "handleDrop", value: function handleDrop(droppedVal, e) {var field = this.props.field;e.preventDefault();if (field.disabled || field.readOnly) { return; } field.removeValue(this.draggedValue); field.addValue(this.draggedValue, field.value.indexOf(droppedVal)); this.triggerOnChange(); } }, { key: "handleTagInteraction", value: function handleTagInteraction( interaction, value, event) { if (isFunction(this.props["onValue" + interaction])) { this.props["onValue" + interaction](this.props.field, value, event); } } }, { key: "beforeAddValue", value: function beforeAddValue( value) {var _this2 = this; if (isFunction(this.props.onBeforeAddValue)) { this.props.onBeforeAddValue(function () {_this2.props.field.addValue(value);}, this.props.field, value); } else { this.props.field.addValue(value); } } }, { key: "beforeRemoveValue", value: function beforeRemoveValue( value) {var _this3 = this; if (isFunction(this.props.onBeforeRemoveValue)) { this.props.onBeforeRemoveValue(function () {_this3.props.field.removeValue(value);}, this.props.field, value); } else { this.props.field.removeValue(value); } } }, { key: "beforeSetValue", value: function beforeSetValue( value) {var _this4 = this; if (isFunction(this.props.onBeforeSetValue)) { this.props.onBeforeSetValue(function () {_this4.props.field.setValue([value]);}, this.props.field, value); } else { this.props.field.setValue([value]); } } }, { key: "render", value: function render() {var _this5 = this; if (this.props.formStore.readMode || this.props.field.readMode) { return this.renderReadMode(); }var _props2 = this.props,classes = _props2.classes,field = _props2.field;var label = field.label,value = field.value,mappingLabel = field.mappingLabel,path = field.path,max = field.max,mappingChildren = field.mappingChildren,data = field.data,selectOnlyLeaf = field.selectOnlyLeaf,expandToSelectedNodes = field.expandToSelectedNodes,disabled = field.disabled,readOnly = field.readOnly,defaultExpanded = field.defaultExpanded,showOnlySearchedNodes = field.showOnlySearchedNodes,validationErrors = field.validationErrors,validationState = field.validationState; var valueTags = void 0; var makeValueTag = function makeValueTag(val) { return ( React.createElement("div", { key: _this5.props.formStore.getGeneratedKey(val, "quickfire-treeselect-values"), tabIndex: "0", disabled: disabled, readOnly: readOnly, title: val[mappingLabel], className: "value-tag quickfire-value-tag btn btn-xs btn-default " + (disabled || readOnly ? "disabled" : ""), draggable: true, onDragEnd: function onDragEnd() {return _this5.draggedValue = null;}, onDragStart: function onDragStart() {return _this5.draggedValue = val;}, onDragOver: function onDragOver(e) {return e.preventDefault();}, onDrop: _this5.handleDrop.bind(_this5, val), onKeyDown: _this5.handleRemoveBackspace.bind(_this5, val), onClick: _this5.handleTagInteraction.bind(_this5, "Click", val), onFocus: _this5.handleTagInteraction.bind(_this5, "Focus", val), onBlur: _this5.handleTagInteraction.bind(_this5, "Blur", val), onMouseOver: _this5.handleTagInteraction.bind(_this5, "MouseOver", val), onMouseOut: _this5.handleTagInteraction.bind(_this5, "MouseOut", val), onMouseEnter: _this5.handleTagInteraction.bind(_this5, "MouseEnter", val), onMouseLeave: _this5.handleTagInteraction.bind(_this5, "MouseLeave", val) }, React.createElement("span", { className: classes.valueDisplay }, isFunction(_this5.props.valueLabelRendering) ? _this5.props.valueLabelRendering(field, val) : field.transformedValueLabel(val)), React.createElement(Glyphicon, { className: classes.remove + " quickfire-remove", glyph: "remove", onClick: _this5.handleRemove.bind(_this5, val) }))); }; if (field.displayValueAsGrouped) { valueTags = []; field.groupedValues.forEach(function (values, groupNode) { valueTags.push( React.createElement("fieldset", { className: classes.valueGroup, key: _this5.props.formStore.getGeneratedKey(groupNode, "quickfire-treeselect-values") }, React.createElement("legend", null, field.groupLabels.get(groupNode) || groupNode[mappingLabel]), values.map(makeValueTag))); }); } else { valueTags = value.map(makeValueTag); } return ( React.createElement(FormGroup, { className: "quickfire-field-tree-select " + (!value.length ? "quickfire-empty-field" : "") + " " + (disabled ? "quickfire-field-disabled" : "") + " " + (readOnly ? "quickfire-field-readonly" : ""), validationState: validationState }, label && React.createElement("div", { onClick: this.handleFocus }, React.createElement(FieldLabel, { field: this.props.field })), React.createElement("div", { disabled: disabled, readOnly: readOnly, className: "form-control input-group " + classes.values, onClick: this.handleFocus }, valueTags, React.createElement("input", { style: { display: "none" }, type: "text", name: "_" + path + "_value", ref: function ref(_ref2) {return _this5.hiddenInputRef = _ref2;} }), React.createElement(Button, { className: "" + classes.openButton, disabled: disabled || readOnly || max !== 1 && value.length >= max }, React.createElement(Glyphicon, { glyph: "list-alt" }))), validationErrors && React.createElement(Alert, { bsStyle: "danger" }, validationErrors.map(function (error) {return React.createElement("p", { key: error }, error);})), React.createElement(Modal, { show: this.state.showTree, onHide: this.handleHideModal }, React.createElement(Modal.Header, { closeButton: true }, React.createElement(FieldLabel, { field: this.props.field }), React.createElement("div", { className: "form-control input-group " + classes.values }, valueTags)), React.createElement(Modal.Body, null, React.createElement(Tree, { mappingLabel: mappingLabel, mappingChildren: mappingChildren, data: data || {}, onSelect: this.handleSelect, selectOnlyLeaf: selectOnlyLeaf, selectedNodes: value, expandToSelectedNodes: expandToSelectedNodes, defaultExpanded: defaultExpanded, showOnlySearchedNodes: showOnlySearchedNodes })), React.createElement(Modal.Footer, null, React.createElement(Button, { className: "quickfire-tree-select-modal-close", onClick: this.handleHideModal }, "Close"))))); } }, { key: "renderReadMode", value: function renderReadMode() {var _this6 = this;var _props$field = this.props.field,value = _props$field.value,disabled = _props$field.disabled,readOnly = _props$field.readOnly;var classes = this.props.classes; return ( React.createElement("div", { className: "quickfire-field-tree-select " + (!value.length ? "quickfire-empty-field" : "") + " quickfire-readmode " + classes.readMode + " " + (disabled ? "quickfire-field-disabled" : "") + " " + (readOnly ? "quickfire-field-readonly" : "") }, React.createElement(FieldLabel, { field: this.props.field }), isFunction(this.props.readModeRendering) ? this.props.readModeRendering(this.props.field) : React.createElement("span", { className: "quickfire-readmode-list" }, value.map(function (value) { return ( React.createElement("span", { key: _this6.props.formStore.getGeneratedKey(value, "dropdown-read-item"), className: "quickfire-readmode-item" }, isFunction(_this6.props.valueLabelRendering) ? _this6.props.valueLabelRendering(_this6.props.field, value) : _this6.props.field.transformedValueLabel(value))); })), React.createElement("input", { style: { display: "none" }, type: "text", ref: function ref(_ref3) {return _this6.hiddenInputRef = _ref3;} }))); } }]);return TreeSelectField;}(React.Component)) || _class) || _class) || _class);export { TreeSelectField as default };