UNPKG

hbp-quickfire

Version:

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

459 lines (283 loc) 31.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 Glyphicon from "react-bootstrap/lib/Glyphicon";import MenuItem from "react-bootstrap/lib/MenuItem";import Alert from "react-bootstrap/lib/Alert";import filter from "lodash/filter";import difference from "lodash/difference";import isFunction from "lodash/isFunction";import isString from "lodash/isString"; import FieldLabel from "./FieldLabel"; import injectStyles from "react-jss"; var styles = { values: { height: "auto", paddingBottom: "3px", position: "relative", "& .btn": { marginRight: "3px", 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" }, remove: { fontSize: "0.8em", opacity: 0.5, marginLeft: "3px", "&:hover": { opacity: 1 } }, options: { width: "100%", maxHeight: "33vh", overflowY: "auto", "&.open": { display: "block" } }, userInput: { background: "transparent", border: "none", color: "currentColor", outline: "none", width: "200px", maxWidth: "33%", marginBottom: "3px" }, topList: { bottom: "100%", top: "auto", margin: "0 0 2px", boxShadow: "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 drop-down list with * an option to allow custom values entered by the user. * The handling of the a custom value is delegated to the application level * through the call of the "onAddCustomValue" callback passed in paramter * @class DropdownSelectField * @memberof FormFields * @namespace DropdownSelectField */var DropdownSelectField = (_dec = inject("formStore"), _dec2 = injectStyles(styles), _dec(_class = _dec2(_class = observer(_class = function (_React$Component) {_inherits(DropdownSelectField, _React$Component); function DropdownSelectField(props) {_classCallCheck(this, DropdownSelectField);var _this = _possibleConstructorReturn(this, (DropdownSelectField.__proto__ || Object.getPrototypeOf(DropdownSelectField)).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. handleInputKeyStrokes = function (e) { var field = _this.props.field; if (field.disabled || field.readOnly) { return; } if (field.allowCustomValues && e.keyCode === 13 && field.value.length < field.max) { //User pressed "Enter" while focus on input and we haven't reached the maximum values if (isFunction(_this.props.onAddCustomValue)) { _this.props.onAddCustomValue(e.target.value.trim(), field, _this.props.formStore); } _this.setState({ userInputValue: "" }); } else if (!e.target.value && field.value.length > 0 && e.keyCode === 8) { // User pressed "Backspace" while focus on input, and input is empty, and values have been entered e.preventDefault(); _this.beforeRemoveValue(field.value[field.value.length - 1]); _this.triggerOnChange(); } else if (e.keyCode === 40) { e.preventDefault(); var allOptions = _this.optionsRef.querySelectorAll(".option"); if (allOptions.length > 0) { allOptions[0].focus(); } } else if (e.keyCode === 38) { e.preventDefault(); var _allOptions = _this.optionsRef.querySelectorAll(".option"); if (_allOptions.length > 0) { _allOptions[_allOptions.length - 1].focus(); } } else if (e.keyCode === 27) { //escape key -> we want to close the dropdown menu _this.closeDropdown(); } };_this. handleChangeUserInput = function (e) { if (_this.props.field.disabled || _this.props.field.readOnly) { return; } e.stopPropagation(); _this.setState({ userInputValue: e.target.value }); };_this. handleFocus = function () { if (_this.props.field.disabled || _this.props.field.readOnly) { return; } _this.inputRef.focus(); _this.listenClickOutHandler(); _this.forceUpdate(); };_this. clickOutHandler = function (e) { if (!_this.wrapperRef || !_this.wrapperRef.contains(e.target)) { _this.unlistenClickOutHandler(); _this.setState({ userInputValue: "" }); } };_this.state = { userInputValue: "" };_this.initField();return _this;}_createClass(DropdownSelectField, [{ key: "initField", value: function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {var _props, field, formStore, optionsUrl, cacheOptionsUrl;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_props = this.props, field = _props.field, formStore = _props.formStore;optionsUrl = field.optionsUrl, cacheOptionsUrl = field.cacheOptionsUrl;if (!optionsUrl) {_context.next = 9;break;}_context.t0 = field;_context.next = 6;return formStore.resolveURL(optionsUrl, cacheOptionsUrl);case 6:_context.t1 = _context.sent;_context.t0.updateOptions.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: "closeDropdown", value: function closeDropdown() {this.wrapperRef = null;this.forceUpdate();} }, { key: "handleRemove", value: function handleRemove(value, e) {if (this.props.field.disabled || this.props.field.readOnly) {return;}e.stopPropagation();this.beforeRemoveValue(value);this.triggerOnChange();} }, { key: "handleRemoveBackspace", value: function handleRemoveBackspace(value, e) {if (this.props.field.disabled || this.props.field.readOnly) {return;} //User pressed "Backspace" while focus on a value if (e.keyCode === 8) {e.preventDefault();this.beforeRemoveValue(value);this.triggerOnChange();this.handleFocus();}} }, { key: "handleSelect", value: function handleSelect(option, e) {var field = this.props.field;if (field.disabled || field.readOnly) {return;}if (!e || e && (!e.keyCode || e.keyCode === 13)) {//If this function call doesn't send an event (->React Bootstrap OnSelect callback) //Or if it comes from a keyboard event associated with the "Enter" key if (e) {e.preventDefault();}if (field.value.length < field.max) {//If we have not reached the maximum values if (isString(option)) {if (field.allowCustomValues && isFunction(this.props.onAddCustomValue)) {this.props.onAddCustomValue(option, field, this.props.formStore);}} else {this.beforeAddValue(option);this.triggerOnChange();}this.setState({ userInputValue: "" });this.handleFocus();}} else if (e && (e.keyCode === 38 || e.keyCode === 40)) {//If it comes from a key board event associated with the "Up" or "Down" key e.preventDefault();var allOptions = this.optionsRef.querySelectorAll(".option");var currentIndex = Array.prototype.indexOf.call(allOptions, e.target);var nextIndex = void 0;if (e.keyCode === 40) {nextIndex = currentIndex + 1 < allOptions.length ? currentIndex + 1 : 0;} else {nextIndex = currentIndex - 1 >= 0 ? currentIndex - 1 : allOptions.length - 1;}allOptions[nextIndex].focus();}} }, { key: "handleDrop", value: function handleDrop(droppedVal, e) {var field = this.props.field;if (field.disabled || field.readOnly) {return;}e.preventDefault();field.removeValue(this.draggedValue);field.addValue(this.draggedValue, field.value.indexOf(droppedVal));if (this.props.field.closeDropdownAfterInteraction) {this.wrapperRef = null;}this.triggerOnChange();this.handleFocus();} }, { key: "listenClickOutHandler", value: function listenClickOutHandler() {window.addEventListener("mouseup", this.clickOutHandler, false);window.addEventListener("touchend", this.clickOutHandler, false);window.addEventListener("keyup", this.clickOutHandler, false);} }, { key: "unlistenClickOutHandler", value: function unlistenClickOutHandler() {window.removeEventListener("mouseup", this.clickOutHandler, false); window.removeEventListener("touchend", this.clickOutHandler, false); window.removeEventListener("keyup", this.clickOutHandler, false); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unlistenClickOutHandler(); } }, { 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); } if (this.props.field.closeDropdownAfterInteraction) { this.wrapperRef = null; } } }, { 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); } if (this.props.field.closeDropdownAfterInteraction) { this.wrapperRef = null; } } }, { key: "handleTagInteraction", value: function handleTagInteraction( interaction, value, event) { if (isFunction(this.props["onValue" + interaction])) { this.props["onValue" + interaction](this.props.field, value, event); } else if (interaction === "Focus") { event.stopPropagation(); this.closeDropdown(); } } }, { key: "render", value: function render() {var _this4 = this; if (this.props.formStore.readMode || this.props.field.readMode) { return this.renderReadMode(); }var _props2 = this.props,classes = _props2.classes,formStore = _props2.formStore;var _props$field = this.props.field,options = _props$field.options,values = _props$field.value,mappingLabel = _props$field.mappingLabel,listPosition = _props$field.listPosition,disabled = _props$field.disabled,readOnly = _props$field.readOnly,max = _props$field.max,allowCustomValues = _props$field.allowCustomValues,customValueLabel = _props$field.customValueLabel,validationErrors = _props$field.validationErrors,validationState = _props$field.validationState; var dropdownOpen = !disabled && !readOnly && values.length < max && this.wrapperRef && this.wrapperRef.contains(document.activeElement); var dropdownClass = dropdownOpen ? "open" : ""; dropdownClass += listPosition === "top" ? " " + classes.topList : ""; var regexSearch = new RegExp(this.state.userInputValue, "gi"); var filteredOptions = []; if (dropdownOpen) { filteredOptions = filter(options, function (option) { return option[mappingLabel] != null && option[mappingLabel].match(regexSearch); }); filteredOptions = difference(filteredOptions, values); } return ( React.createElement("div", { ref: function ref(_ref5) {return _this4.wrapperRef = _ref5;} }, React.createElement(FormGroup, { onClick: this.handleFocus, className: "quickfire-field-dropdown-select " + (!values.length ? "quickfire-empty-field" : "") + " " + (disabled ? "quickfire-field-disabled" : "") + " " + (readOnly ? "quickfire-field-readonly" : ""), validationState: validationState }, React.createElement(FieldLabel, { field: this.props.field }), React.createElement("div", { disabled: disabled, readOnly: readOnly, className: "form-control " + classes.values }, values.map(function (value) { return ( React.createElement("div", { key: formStore.getGeneratedKey(value, "quickfire-dropdown-item-button"), tabIndex: "0", className: "value-tag quickfire-value-tag btn btn-xs btn-default " + (disabled || readOnly ? "disabled" : ""), disabled: disabled, readOnly: readOnly, draggable: true, onDragEnd: function onDragEnd() {return _this4.draggedValue = null;}, onDragStart: function onDragStart() {return _this4.draggedValue = value;}, onDragOver: function onDragOver(e) {return e.preventDefault();}, onDrop: _this4.handleDrop.bind(_this4, value), onKeyDown: _this4.handleRemoveBackspace.bind(_this4, value), onClick: _this4.handleTagInteraction.bind(_this4, "Click", value), onFocus: _this4.handleTagInteraction.bind(_this4, "Focus", value), onBlur: _this4.handleTagInteraction.bind(_this4, "Blur", value), onMouseOver: _this4.handleTagInteraction.bind(_this4, "MouseOver", value), onMouseOut: _this4.handleTagInteraction.bind(_this4, "MouseOut", value), onMouseEnter: _this4.handleTagInteraction.bind(_this4, "MouseEnter", value), onMouseLeave: _this4.handleTagInteraction.bind(_this4, "MouseLeave", value), title: value[mappingLabel] }, React.createElement("span", { className: classes.valueDisplay }, isFunction(_this4.props.valueLabelRendering) ? _this4.props.valueLabelRendering(_this4.props.field, value) : value[mappingLabel]), React.createElement(Glyphicon, { className: classes.remove + " quickfire-remove", glyph: "remove", onClick: _this4.handleRemove.bind(_this4, value) }))); }), React.createElement("input", { className: "quickfire-user-input " + classes.userInput, onDrop: this.handleDrop.bind(this, null), onDragOver: function onDragOver(e) {return e.preventDefault();}, ref: function ref(_ref2) {return _this4.inputRef = _ref2;}, type: "text", onKeyDown: this.handleInputKeyStrokes, onChange: this.handleChangeUserInput, onFocus: this.handleFocus, value: this.state.userInputValue, disabled: readOnly || disabled || values.length >= max }), React.createElement("input", { style: { display: "none" }, type: "text", ref: function ref(_ref3) {return _this4.hiddenInputRef = _ref3;} }), dropdownOpen && (filteredOptions.length || this.state.userInputValue) ? React.createElement("ul", { className: "quickfire-dropdown dropdown-menu " + classes.options + " " + dropdownClass, ref: function ref(_ref4) {_this4.optionsRef = _ref4;} }, !allowCustomValues && this.state.userInputValue && filteredOptions.length === 0 ? React.createElement(MenuItem, { key: "no-options", className: "quickfire-dropdown-item" }, React.createElement("em", null, "No options available for: "), " ", React.createElement("strong", null, this.state.userInputValue)) : null, allowCustomValues && this.state.userInputValue ? React.createElement(MenuItem, { className: "quickfire-dropdown-item", key: this.state.userInputValue, onSelect: this.handleSelect.bind(this, this.state.userInputValue) }, React.createElement("div", { tabIndex: -1, className: "option", onKeyDown: this.handleSelect.bind(this, this.state.userInputValue) }, React.createElement("em", null, customValueLabel, "\xA0"), " ", React.createElement("strong", null, this.state.userInputValue))) : null, filteredOptions.map(function (option) { return ( React.createElement(MenuItem, { className: "quickfire-dropdown-item", key: formStore.getGeneratedKey(option, "quickfire-dropdown-list-item"), onSelect: _this4.handleSelect.bind(_this4, option) }, React.createElement("div", { tabIndex: -1, className: "option", onKeyDown: _this4.handleSelect.bind(_this4, option) }, option[mappingLabel]))); })) : null), validationErrors && React.createElement(Alert, { bsStyle: "danger" }, validationErrors.map(function (error) {return React.createElement("p", { key: error }, error);}))))); } }, { key: "renderReadMode", value: function renderReadMode() {var _this5 = this;var _props$field2 = this.props.field,value = _props$field2.value,mappingLabel = _props$field2.mappingLabel,disabled = _props$field2.disabled,readOnly = _props$field2.readOnly;var classes = this.props.classes; return ( React.createElement("div", { className: "quickfire-field-dropdown-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: _this5.props.formStore.getGeneratedKey(value, "dropdown-read-item"), className: "quickfire-readmode-item" }, isFunction(_this5.props.valueLabelRendering) ? _this5.props.valueLabelRendering(_this5.props.field, value) : value[mappingLabel])); })), React.createElement("input", { style: { display: "none" }, type: "text", ref: function ref(_ref6) {return _this5.hiddenInputRef = _ref6;} }))); } }]);return DropdownSelectField;}(React.Component)) || _class) || _class) || _class);export { DropdownSelectField as default };