UNPKG

@arche-mc2/arche-controls

Version:

We know that there are a ton of react UI library projects to choose from. Our hope with this one is to provide the next generation of react components that you can use to bootstrap your next project, or as a reference for building a UIKit. Read on to get

507 lines 28.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = require("react"); var update = require("react-addons-update"); var classnames = require("classnames"); var Select = require("react-select"); var axios_1 = require("axios"); var BaseControl_1 = require("../_Common/BaseControl/BaseControl"); var queryString = require("query-string"); var eventListener_1 = require("../../../Common/utils/eventListener"); var utils_1 = require("../../../Common/utils"); var theming_1 = require("../../../Common/theming/"); var UpLigne_1 = require("../../Display/Ligne/UpLigne"); var styles_1 = require("./styles"); var _ = require("lodash"); var types_1 = require("../../../Common/utils/types"); var CancelToken = axios_1.default.CancelToken; var formatGroupLabel = function (data) { return (React.createElement("div", { style: styles_1.groupStyles }, React.createElement("span", null, data.label), React.createElement("span", { style: styles_1.groupBadgeStyles }, data.options.length))); }; var formatMinimumInputLenghMessage = function (minimumInputLength) { return "Veuillez renseigner au minimum " + minimumInputLength + " caract\u00E8res"; }; var UpSelect = (function (_super) { tslib_1.__extends(UpSelect, _super); function UpSelect(p, c) { var _this = _super.call(this, p, c) || this; _this.setSelect = function (input) { if (_this.selectElement == undefined) { _this.selectElement = input; } }; _this.setValue = function (receiveValue) { var valueToParse = Array.isArray(receiveValue) ? tslib_1.__spreadArrays(receiveValue) : tslib_1.__assign({}, receiveValue); if (_this.props.multiple === true) { var isPairArray = _this.isPairArray(receiveValue); var newState = null; if (isPairArray === true) { var extra = _this.state.extra === undefined || _this.state.extra === null ? {} : tslib_1.__assign({}, _this.state.extra); extra.fullObject = receiveValue; newState = tslib_1.__assign(tslib_1.__assign({}, _this.state), { extra: extra }); } else if (isPairArray == false && Array.isArray(receiveValue) === true && _this.props.data != null) { var extra = _this.state.extra === undefined || _this.state.extra === null ? {} : tslib_1.__assign({}, _this.state.extra); var data = _this.makePairFromIds(receiveValue); extra.fullObject = data; newState = tslib_1.__assign(tslib_1.__assign({}, _this.state), { extra: extra }); return _this.parseValue(data); } else if (receiveValue == null) { newState = update(_this.state, { extra: { fullObject: { $set: null } } }); } if (newState != null && _this.props.closeMenuOnSelect) { newState.extra.menuIsOpen = false; } _this.setState(newState); } else { var isPair = _this.isPair(receiveValue); var newState = null; if (isPair === true) { var extra = _this.state.extra === undefined || _this.state.extra === null ? {} : tslib_1.__assign({}, _this.state.extra); extra.fullObject = receiveValue; newState = { extra: extra }; } else if (isPair === false && _this.props.data != null) { var data = _this.makePairFromId(receiveValue); var extra = _this.state.extra === undefined || _this.state.extra === null ? {} : tslib_1.__assign({}, _this.state.extra); extra.fullObject = data; newState = { extra: extra }; valueToParse = data; } else if (receiveValue == null) { newState = update(_this.state, { extra: { fullObject: { $set: null } } }); } if (newState != null && _this.props.closeMenuOnSelect) { newState.extra.menuIsOpen = false; } _this.setState(newState); } return _this.parseValue(valueToParse); }; _this.makePairFromIds = function (ids) { return ids.map(_this.makePairFromId).filter(function (v) { return v !== null; }); }; _this.makePairFromId = function (id) { var _a; for (var i = 0; i < _this.props.data.length; i++) { if (_this.props.data[i][_this.keyId] === id) { return _a = {}, _a[_this.keyId] = _this.props.data[i][_this.keyId], _a[_this.keyText] = _this.props.data[i][_this.keyText], _a; } } return null; }; _this.isPairArray = function (obj) { if (obj == null || Array.isArray(obj) == false) { return false; } return obj.every(_this.isPair); }; _this.isPair = function (obj) { if (obj == null) { return false; } if ((obj.hasOwnProperty(_this.keyId) && obj.hasOwnProperty(_this.keyText)) || (obj.hasOwnProperty("id") && obj.hasOwnProperty("text"))) { return true; } var regexp = /{-?[\w]+}/gi; var arr = _this.keyText.match(regexp); if (arr === null) { return obj.hasOwnProperty(_this.keyId) && obj.hasOwnProperty(_this.keyText); } else { for (var text in arr) { var sourceText = text.replace("{", "").replace("}", ""); if (obj.hasOwnProperty(sourceText) == false) { return false; } } return obj.hasOwnProperty(_this.keyId); } }; _this.defaultIsOptionIsSelected = function (option, selectedOptions) { return selectedOptions.find(function (o) { return o[_this.keyId] === option[_this.keyId]; }) != null; }; _this.parseValue = function (receiveValue) { if (_this.props.returnType === "id" && typeof (receiveValue) === "object" && receiveValue != null) { if (_this.props.multiple === true && Array.isArray(receiveValue)) { return receiveValue.map((function (v) { return v != null ? (v[_this.keyId] || v["id"] || v) : null; })); } else { return receiveValue[_this.keyId] || receiveValue["id"]; } } return receiveValue; }; _this.getOptionLabel = function (option) { return option[_this.keyText]; }; _this.formatOptionLabel = function (option) { var color = option.color; var text = _this.getOptionLabel(option); return (React.createElement("div", { style: { display: "flex", alignItems: "center", cursor: 'pointer' } }, color && React.createElement("div", { style: { background: color, borderRadius: 6, height: 6, width: 6, marginRight: 6 } }), text)); }; _this.getOptionRenderer = function (option) { if (_this.props.optionRenderer) { var OptionRenderer = _this.props.optionRenderer; return (React.createElement(OptionRenderer, tslib_1.__assign({}, option))); } else { if (option[_this.keyId]) return (React.createElement("span", { key: "option_" + option[_this.keyId] }, _this.format(option, _this.keyText))); else return (React.createElement("span", { key: "option_" + option["id"] }, _this.format(option, option["text"]))); } }; _this.getValueRenderer = function (value) { if (_this.props.valueRenderer) { var ValueRenderer = _this.props.valueRenderer; return (React.createElement(ValueRenderer, tslib_1.__assign({}, value))); } else { if (value[_this.keyId]) return (React.createElement("span", { key: "option_" + value[_this.keyId] }, _this.format(value, _this.keyText))); else return (React.createElement("span", { key: "option_" + value["id"] }, _this.format(value, value["text"]))); } }; _this.filterOptions = function (option, filter) { var filterMatched = !filter || (option.label != null && (typeof option.label == "object" || ("" + option.label).toLowerCase().includes(filter.toLowerCase()))); return filterMatched; }; _this.findInObject = function (object, path) { var local = path.shift(); if (path.length === 0) { return object[local]; } else { return _this.findInObject(object[local], path); } }; _this.formatCreateLabel = function (inputValue) { if (_this.props.formatCreateLabel != null) { return _this.props.formatCreateLabel(inputValue); } return React.createElement("p", null, "Cr\u00E9er \"" + inputValue + "\""); }; _this.inputDoesntMatchSelectValue = function (inputValue, selectValue) { return (selectValue == null || selectValue.filter(function (option) { return option[_this.keyText] && option[_this.keyText].toLowerCase() == inputValue.toLowerCase(); }).length == 0); }; _this.inputDoesntMatchOneOfSelectOptions = function (inputValue, selectOptions) { return (selectOptions == null || selectOptions.filter(function (option) { return option[_this.keyText] && option[_this.keyText].toLowerCase() == inputValue.toLowerCase(); }).length == 0); }; _this.isValidNewOption = function (inputValue, selectValue, selectOptions) { if (_this.props.isValidNewOption != null) { return _this.props.isValidNewOption(inputValue, selectValue, selectOptions); } var isValidNewOption = !utils_1.isEmpty(inputValue) && _this.inputDoesntMatchSelectValue(inputValue, selectValue) && _this.inputDoesntMatchOneOfSelectOptions(inputValue, selectOptions); return isValidNewOption; }; _this.getNewOptionData = function (inputValue, optionLabel) { var _a; if (_this.props.getNewOptionData != null) { return _this.props.getNewOptionData(inputValue, optionLabel); } return _a = {}, _a[_this.keyText] = optionLabel, _a[_this.keyId] = inputValue, _a.__isNew__ = true, _a; }; _this.getLoadOptions = function () { var loadOptions = null; if (_this.props.dataSource !== undefined) { var dataSource_1 = _this.props.dataSource; var queryParam_1 = _this.props.dataSource.queryParameterName || 'search'; var minimumInputLength_1 = _this.props.autoload ? 0 : _this.props.minimumInputLength; loadOptions = function (input) { if (minimumInputLength_1 && input.length < minimumInputLength_1) { if (input.length !== 0) { var newState = update(_this.state, { extra: { loadingPlaceholder: { $set: _this.props.formatMinimumInputLenghMessage(minimumInputLength_1) } } }); _this.setState(newState); } else { var newState = update(_this.state, { extra: { loadingPlaceholder: { $set: _this.props.loadingPlaceholder } } }); _this.setState(newState); } return false; } else { var newState = update(_this.state, { extra: { loadingPlaceholder: { $set: _this.props.loadingPlaceholder } } }); _this.setState(newState); } if (_this.timeOutLoadOptions) { clearTimeout(_this.timeOutLoadOptions); } if (_this.axiosSource) { _this.axiosSource.cancel('Next request in progress'); } if (_this.props.dataSource.fetchData) { return _this.props.dataSource.fetchData(input, _this.props.dataSource.defaultParameters) .then(function (data) { if (dataSource_1.handleResponse) { data = dataSource_1.handleResponse(data); } return data; }).catch(function (thrown) { throw thrown; }); } var qs = queryParam_1 + "=" + input; if (dataSource_1.getExtraParams) { var params = dataSource_1.getExtraParams(); if (params) { qs += "&" + queryString.stringify(params); } } var query = dataSource_1.query + "?" + qs; if (dataSource_1.endPoint) { query = dataSource_1.endPoint + "/" + query; } _this.axiosSource = CancelToken.source(); return axios_1.default.get(query, { cancelToken: _this.axiosSource.token }).then(function (response) { var data = response.data; if (dataSource_1.handleResponse) { data = dataSource_1.handleResponse(data); } _this.axiosSource = null; return data; }).catch(function (thrown) { if (axios_1.default.isCancel(thrown)) { console.log('Request canceled', thrown.message); } this.axiosSource = null; throw thrown; }); }; loadOptions = loadOptions.bind(_this); } return loadOptions; }; _this.onChange = function (name, value, action) { _this.setValue(value); _this.handleChangeEvent(eventListener_1.eventFactory(name || _this.props.name, value), value); }; _this.state = { value: (p.value) ? _this.parseValue(p.value) : p.default, extra: { loadingPlaceholder: p.loadingPlaceholder, fullObject: (p.value) ? p.value : p.default, } }; return _this; } UpSelect.prototype.componentDidMount = function () { var _this = this; var loadOptions = this.getLoadOptions(); if (this.props.autoload && loadOptions != null) { this.setState(update(this.state, { extra: { isDataFetching: { $set: true } } })); loadOptions("").then(function (data) { _this.setState(update(_this.state, { extra: { isDataFetching: { $set: false }, loadedData: { $set: data } } }), function () { if (!_.isEmpty(_this.state.extra.loadedData) && _this.state.extra.loadedData.length == 1) { _this.onChange(_this.props.name, _this.state.extra.loadedData[0], null); } }); }).catch(function (e) { return _this.setState(update(_this.state, { extra: { isDataFetching: { $set: false } } })); }); } }; Object.defineProperty(UpSelect.prototype, "keyId", { get: function () { if (this.props.dataSource) { return this.props.dataSource.id || "id"; } return this.props.valueKey || "id"; }, enumerable: true, configurable: true }); Object.defineProperty(UpSelect.prototype, "keyText", { get: function () { if (this.props.dataSource) { return this.props.dataSource.text || "text"; } return this.props.labelKey || "text"; }, enumerable: true, configurable: true }); UpSelect.prototype.isEmpty = function (value) { return value === null || value === undefined || value === ""; }; UpSelect.prototype.getValue = function (data) { var _this = this; if (data == null) { return null; } if (this.props.returnType === "id") { var fullobject = data; if (this.props.multiple && fullobject != null) { return fullobject .map(function (v) { if (v != null && (v.hasOwnProperty(_this.keyId))) return v[_this.keyId] != null ? v[_this.keyId] : null; else if (v != null && (v.hasOwnProperty("id"))) return v["id"] != null ? v["id"] : null; else return null; }) .filter(function (v) { return v !== null; }); } else { if (fullobject != null && fullobject.hasOwnProperty(this.keyId)) return fullobject[this.keyId]; else if (fullobject != null && fullobject.hasOwnProperty("id")) return fullobject["id"]; } } else { return data; } }; UpSelect.prototype.format = function (object, strFormat) { var regexp = /{-?[\w]+}/gi; var arr = strFormat.match(regexp); if (arr === null) { return object[strFormat] || object["text"]; } for (var i = 0; i < arr.length; i++) { var sourceText = arr[i].replace("{", "").replace("}", ""); strFormat = strFormat.replace(arr[i], this.findInObject(object, sourceText.split("."))); } return strFormat; }; UpSelect.prototype.showError = function () { return this.props.showError !== undefined ? this.props.showError === true : this.hasError; }; UpSelect.prototype.showSuccess = function () { return this.props.showSuccess; }; UpSelect.prototype.renderControl = function () { var _this = this; var dataSource = this.props.dataSource; var loadOptions = this.getLoadOptions(); var data = this.props.data || this.state.extra.loadedData; var specProps = { options: data, loadOptions: false, }; if (this.state.extra.loadedData == null && loadOptions != null) { specProps = { loadOptions: loadOptions, autoload: this.props.autoload }; } else { dataSource = null; } var allowCreate = this.props.allowCreate; var formatCreateLabel = undefined; var isValidNewOption = undefined; if (this.props.isSearchable && !allowCreate) { var emptyFormatCreateLabel = function (s) { return ""; }; var emptyIsValidNewOption = function () { return false; }; allowCreate = true; formatCreateLabel = emptyFormatCreateLabel; isValidNewOption = emptyIsValidNewOption; } if (this.props.isSearchable) { specProps.allowCreateWhileLoading = this.props.allowCreateWhileLoading; specProps.formatCreateLabel = formatCreateLabel || this.formatCreateLabel; specProps.isValidNewOption = isValidNewOption || this.isValidNewOption; specProps.getNewOptionData = this.getNewOptionData; specProps.onCreateOption = this.props.onCreateOption; specProps.createOptionPosition = this.props.createOptionPosition; } else if (this.props.allowCreate) { specProps.allowCreateWhileLoading = this.props.allowCreateWhileLoading; specProps.formatCreateLabel = this.formatCreateLabel; specProps.isValidNewOption = this.isValidNewOption; specProps.getNewOptionData = this.getNewOptionData; specProps.onCreateOption = this.props.onCreateOption; specProps.createOptionPosition = this.props.createOptionPosition; } var value = this.isControlled ? this.props.value : this.state.extra.fullObject; if (this.props.returnType == 'id') { if (this.props.multiple && value && typeof value[0] !== 'object') { value = data && data.filter(function (item) { return value.indexOf(item.id) >= 0; }); } else if (typeof value !== 'object' && data) { value = data.find(function (item) { return item.id == value; }); } else if (typeof value !== 'object' && this.state.extra.fullObject) { value = this.state.extra.fullObject; } } var selectComponentProps = tslib_1.__assign(tslib_1.__assign({}, specProps), { value: value, color: '#354052', name: this.props.name, placeholder: this.props.floatingLabel ? '' : this.props.placeholder, filterOption: function (option, filter) { var filterHandler = _this.props.filterOptions || _this.filterOptions; return filterHandler(option, filter); }, allowCreate: allowCreate, promptTextCreator: this.props.promptTextCreator, autoBlur: false, isLoading: this.state.extra.isDataFetching || this.props.isLoading, loadingMessage: function (input) { return _this.state.extra.loadingPlaceholder; }, isMulti: this.props.multiple, isClearable: this.props.allowClear, isDisabled: this.props.disabled, noOptionsMessage: function (inputValue) { return (_this.props.autoload && _this.state.extra.isDataFetching) ? _this.state.extra.loadingPlaceholder : _this.props.noResultsText; }, clearAllText: this.props.clearAllText, clearValueText: this.props.clearValueText, addLabelText: this.props.addLabelText, searchPromptText: this.props.searchPromptText, optionRenderer: this.getOptionRenderer, valueRenderer: this.getValueRenderer, onChange: this.onChange.bind(this, this.props.name), menuIsOpen: this.state.extra.menuIsOpen, onMenuOpen: function () { return _this.setState(update(_this.state, { extra: { menuIsOpen: { $set: true } } })); }, onMenuClose: function () { return _this.setState(update(_this.state, { extra: { menuIsOpen: { $set: false } } })); }, onInputChange: function (inputValue) { return _this.setState(update(_this.state, { extra: { inputValue: { $set: inputValue } } })); }, getOptionLabel: this.getOptionLabel, getOptionValue: function (option) { return _this.parseValue(option); }, inputValue: this.state.extra.inputValue, defaultInputValue: "", formatGroupLabel: this.props.formatGroupLabel, formatOptionLabel: this.props.formatOptionLabel, isOptionDisabled: this.props.isOptionDisabled, isOptionSelected: this.props.isOptionSelected || this.defaultIsOptionIsSelected, isRtl: this.props.isRtl, isSearchable: this.props.isSearchable, minMenuHeight: this.props.minMenuHeight, maxMenuHeight: this.props.maxMenuHeight, menuPlacement: this.props.menuPlacement, menuShouldBlockScroll: this.props.menuShouldBlockScroll, menuShouldScrollIntoView: this.props.menuShouldScrollIntoView, onBlur: this.props.onBlur, onFocus: this.props.onFocus, onKeyDown: this.props.onKeyDown, onMenuScrollToBottom: this.props.onMenuScrollToBottom, onMenuScrollToTop: this.props.onMenuScrollToTop, openMenuOnFocus: this.props.openMenuOnFocus, openMenuOnClick: this.props.openMenuOnClick, closeMenuOnSelect: this.props.closeMenuOnSelect, ref: function (input) { return _this.input = input; }, styles: styles_1.customStyles(this.props.theme, this.state.value) }); var _a = this.props, floatingLabel = _a.floatingLabel, disabled = _a.disabled, readonly = _a.readonly; var FloatingLabel = floatingLabel && (React.createElement("label", { onClick: function () { var _a; if (disabled || readonly) return; (_a = _this.input) === null || _a === void 0 ? void 0 : _a.focus(); _this.setState(update(_this.state, { extra: { menuIsOpen: { $set: true } } })); }, style: { cursor: 'pointer' }, className: classnames('up-select-label', { 'up-select-label-focused': !!this.state.extra.menuIsOpen, 'up-select-label-valued': !!value }) }, floatingLabel, this.props.isRequired ? (React.createElement(UpLigne_1.default, { className: "up-select-label-star" }, "*")) : (''))); return (React.createElement("div", tslib_1.__assign({ className: classnames(this.props.className, styles_1.getLabelStyle(this.props), 'up-select-wrapper') }, types_1.getTestableComponentProps(this.props)), dataSource != null && allowCreate === true && (React.createElement(React.Fragment, null, FloatingLabel, React.createElement(Select.AsyncCreatable, tslib_1.__assign({}, selectComponentProps)))), dataSource != null && allowCreate === false && (React.createElement(React.Fragment, null, FloatingLabel, React.createElement(Select.Async, tslib_1.__assign({}, selectComponentProps)))), dataSource == null && allowCreate === true && (React.createElement(React.Fragment, null, FloatingLabel, React.createElement(Select.Creatable, tslib_1.__assign({}, selectComponentProps)))), dataSource == null && allowCreate === false && (React.createElement(React.Fragment, null, FloatingLabel, React.createElement(Select.SelectBase, tslib_1.__assign({}, selectComponentProps)))))); }; UpSelect.defaultProps = { noResultsText: "Aucun résultat trouvé", clearAllText: "Effacer", clearValueText: "Déselectionner", addLabelText: 'Ajouter "{label}" ?', searchPromptText: "-- Rechercher", placeholder: "-- Sélectionner", loadingPlaceholder: "Chargement en cours...", default: null, autoload: false, showError: true, isLoading: false, allowCreate: false, returnType: "full", formatGroupLabel: formatGroupLabel, formatMinimumInputLenghMessage: formatMinimumInputLenghMessage, isRtl: false, isSearchable: true, minMenuHeight: 140, maxMenuHeight: 300, menuPlacement: 'auto', menuShouldBlockScroll: false, menuShouldScrollIntoView: true, openMenuOnFocus: false, openMenuOnClick: true, tabIndex: 0, closeMenuOnSelect: true, createOptionPosition: 'last', theme: theming_1.default }; return UpSelect; }(BaseControl_1.BaseControlComponent)); exports.default = UpSelect; ; //# sourceMappingURL=UpSelect.js.map