all files / src/ SelectFormField.jsx

84.68% Statements 210/248
74.43% Branches 131/176
80% Functions 36/45
91.59% Lines 196/214
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575                                                              12×     96×   19×   19×                                               19×   19×   19× 19×   19×       19×     19× 19×                                                                                                                                                                               23× 23× 23×       23×       23× 48×       48×           23×                                                                       30×   30× 30× 30× 28×   30× 13×   17×       13×     11×             28× 28× 28×         28×   28× 28× 28×   28× 28×     28×   28× 23×   32×                                             23×     23× 943× 74×       23× 23×     23×         23× 14×     23×       23×                                                                               28×         28× 28×   28×           28×                                                                                                                         48×            
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
 
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
 
var _react = require('react');
 
var _react2 = _interopRequireDefault(_react);
 
var _propTypes = require('prop-types');
 
var _propTypes2 = _interopRequireDefault(_propTypes);
 
var _uxcoreFormField = require('uxcore-form-field');
 
var _uxcoreFormField2 = _interopRequireDefault(_uxcoreFormField);
 
var _uxcoreConst = require('uxcore-const');
 
var _uxcoreConst2 = _interopRequireDefault(_uxcoreConst);
 
var _uxcoreSelect = require('uxcore-select2');
 
var _uxcoreSelect2 = _interopRequireDefault(_uxcoreSelect);
 
var _objectAssign = require('object-assign');
 
var _objectAssign2 = _interopRequireDefault(_objectAssign);
 
var _isObject = require('lodash/isObject');
 
var _isObject2 = _interopRequireDefault(_isObject);
 
var _isEqual = require('lodash/isEqual');
 
var _isEqual2 = _interopRequireDefault(_isEqual);
 
var _nattyFetch = require('natty-fetch');
 
var _nattyFetch2 = _interopRequireDefault(_nattyFetch);
 
var _lie = require('lie');
 
var _lie2 = _interopRequireDefault(_lie);
 
var _find = require('lodash/find');
 
var _find2 = _interopRequireDefault(_find);
 
var _util = require('./util');
 
var _util2 = _interopRequireDefault(_util);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
 
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
 
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { Eif (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
function _possibleConstructorReturn(self, call) { Iif (!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) { Iif (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 } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * Created by xy on 15/4/13.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
 
 
var processData = _util2['default'].processData,
    transferDataToObj = _util2['default'].transferDataToObj,
    getValuePropValue = _util2['default'].getValuePropValue;
 
var defaultLabels = {
  placeholder: {
    'zh-cn': '请下拉选择',
    'en-us': 'Please select',
    en: 'Please select'
  },
  notFoundContent: {
    'zh-cn': '未查询到备选项',
    'en-us': 'No Options Found',
    en: 'No Options Found'
  }
};
 
var Option = _uxcoreSelect2['default'].Option;
 
var selectOptions = ['allowClear', 'autoClearSearchValue', 'autoFocus', 'backfill', 'combobox', 'defaultActiveFirstOption', 'defaultOpen', 'disabled', 'dropdownAlign', 'dropdownClassName', 'dropdownMatchSelectWidth', 'dropdownMenuStyle', 'dropdownRender', 'dropdownStyle', 'filterOption', 'firstActiveValue', 'getInputElement', 'getPopupContainer', 'labelInValue', 'loading', 'maxTagCount', 'maxTagPlaceholder', 'maxTagTextLength', 'menuItemSelectedIcon', 'multiple', 'notFoundContent', 'onBlur', 'onDeselect', 'onFocus', 'onInputKeyDown', 'onPopupScroll', 'open', 'optionFilterProp', 'optionLabelProp', 'placeholder', 'rcRef', 'searchPlaceholder', 'showAction', 'showArrow', 'showSearch', 'tags'];
 
var SelectFormField = function (_FormField) {
  _inherits(SelectFormField, _FormField);
 
  function SelectFormField(props) {
    _classCallCheck(this, SelectFormField);
 
    var _this = _possibleConstructorReturn(this, _FormField.call(this, props));
 
    var me = _this;
    var jsxdata = props.jsxdata;
 
    (0, _objectAssign2['default'])(me.state, {
      data: processData(jsxdata),
      prevPropsData: jsxdata
    });
    return _this;
  }
 
  SelectFormField.prototype.componentDidMount = function componentDidMount() {
    _FormField.prototype.componentDidMount.call(this);
    if (this.props.jsxfetchUrl && this.props.fetchDataOnMount) {
      this.fetchData();
    }
  };
 
  SelectFormField.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    _FormField.prototype.componentDidUpdate.call(this, prevProps, prevState);
    var jsxfetchUrl = this.props.jsxfetchUrl;
 
    Iif (jsxfetchUrl && prevProps.jsxfetchUrl !== jsxfetchUrl) {
      this.fetchData();
    }
  };
 
  /**
   * select inner method is used, not very reliable
   * 
   * @deprecated
   */
  /* eslint-disable */
 
 
  SelectFormField.prototype.resetSelect = function resetSelect() {
    console.warn('Method resetSelect is deprecated');
  };
  /* eslint-enable */
 
  SelectFormField.prototype.fetchData = function fetchData(value) {
    var _this2 = this;
 
    if (this.fetch) {
      this.fetch.abort();
    }
 
    var formerData = this.state.data;
 
    this.setState({
      data: [],
      loading: true
    });
 
    var _props = this.props,
        jsxfetchUrl = _props.jsxfetchUrl,
        dataType = _props.dataType,
        beforeFetch = _props.beforeFetch,
        afterFetch = _props.afterFetch,
        method = _props.method,
        fitResponse = _props.fitResponse,
        jsxdata = _props.jsxdata;
 
 
    this.fetch = _nattyFetch2['default'].create({
      url: jsxfetchUrl,
      jsonp: dataType ? dataType === 'jsonp' : /\.jsonp/.test(jsxfetchUrl),
      data: beforeFetch({
        q: value
      }),
      method: method,
      fit: fitResponse,
      Promise: _lie2['default']
    });
 
    this.fetch().then(function (content) {
      var fetchData = processData(afterFetch(content));
      Eif (jsxdata) {
        fetchData = processData(jsxdata).concat(fetchData);
      }
      _this2.setState({
        data: fetchData,
        loading: false
      });
    })['catch'](function (e) {
      console.error(e.stack);
 
      _this2.setState({
        data: formerData,
        loading: false
      });
    });
  };
 
  SelectFormField.prototype.handleChange = function handleChange(value) {
    var _props2 = this.props,
        useValueText = _props2.useValueText,
        jsxfetchUrl = _props2.jsxfetchUrl,
        onSearch = _props2.onSearch,
        labelInValue = _props2.labelInValue;
 
    var labelInValueMode = !!jsxfetchUrl || !!onSearch || labelInValue;
    if (labelInValueMode && useValueText) {
      var newValue = value;
      Iif (Array.isArray(value)) {
        newValue = value.map(function (item) {
          return {
            value: item.key,
            text: item.label
          };
        });
      }
      Eif ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
        newValue = {
          value: value.key,
          text: value.label
        };
      }
      this.handleDataChange(newValue);
    } else {
      this.handleDataChange(value);
    }
  };
 
  SelectFormField.prototype.handleSearch = function handleSearch(value) {
    var me = this;
    if (me.searchTimer) {
      clearTimeout(me.searchTimer);
    }
    me.searchTimer = setTimeout(function () {
      Eif (me.props.jsxfetchUrl) {
        me.fetchData(value);
      } else if (me.props.onSearch) {
        me.props.onSearch(value);
      }
    }, me.props.searchDelay);
  };
 
  SelectFormField.prototype._generateOptionsFromData = function _generateOptionsFromData() {
    var me = this;
    var values = me.state.data;
    var _me$props = me.props,
        children = _me$props.children,
        optionTextRender = _me$props.optionTextRender;
 
    if (!values.length) {
      Iif (children) {
        return children;
      }
    }
    var arr = values.map(function (item) {
      var value = item.value,
          text = item.text,
          others = _objectWithoutProperties(item, ['value', 'text']);
 
      return _react2['default'].createElement(
        Option,
        _extends({ key: value, title: text }, others),
        optionTextRender ? optionTextRender(item.text, item) : item.text
      );
    });
    return arr;
  };
 
  /**
   * 获取当前已经选择项的完整数据
   * 多选时返回数组,单选时返回 object
   * 新增 value is object。
   */
 
 
  SelectFormField.prototype.getFullData = function getFullData() {
    var _state = this.state,
        data = _state.data,
        value = _state.value;
 
    if (Array.isArray(value)) {
      return value.map(function (selectItem) {
        Iif ((0, _isObject2['default'])(selectItem)) {
          return (0, _find2['default'])(data, function (item) {
            return item.value === selectItem.key;
          });
        }
        return (0, _find2['default'])(data, function (item) {
          return item.value === selectItem;
        });
      }).filter(function (i) {
        return i !== undefined;
      });
    }
    Iif ((0, _isObject2['default'])(value)) {
      return (0, _find2['default'])(data, function (item) {
        return item.value === value.key;
      });
    }
    return (0, _find2['default'])(data, function (item) {
      return item.value === value;
    });
  };
 
  /**
   * transfer 'a' to { key: 'a' }
   * transfer ['a'] to [{ key: 'a' }]
   * transfer { value: 'a', text: 'A' } to { key: 'a', label: 'A' }
   * transfer [{ value: 'a', text: 'A' }] to [{ key: 'x', label: 'A' }]
   */
 
 
  SelectFormField.prototype.processValue = function processValue(value) {
    var _this3 = this;
 
    var me = this;
    var newValue = value;
    if (value === undefined) {
      newValue = me.state.value;
    }
    if (!me.props.jsxfetchUrl && !me.props.onSearch) {
      return newValue;
    }
    if (typeof newValue === 'string') {
      return {
        key: newValue
      };
    }
    if (newValue instanceof Array) {
      return newValue.map(function (item) {
        return _this3.processValue(item);
      });
    }
    if ((typeof newValue === 'undefined' ? 'undefined' : _typeof(newValue)) === 'object' && newValue !== null) {
      return {
        key: newValue.value || newValue.key,
        label: newValue.text || newValue.label
      };
    }
    return newValue;
  };
 
  SelectFormField.prototype.addSpecificClass = function addSpecificClass() {
    var me = this;
    Eif (me.props.jsxprefixCls === 'kuma-uxform-field') {
      return me.props.jsxprefixCls + ' kuma-select-uxform-field';
    }
    return me.props.jsxprefixCls;
  };
 
  SelectFormField.prototype.renderField = function renderField() {
    var _this4 = this;
 
    var me = this;
    var arr = [];
    var mode = me.props.jsxmode || me.props.mode;
 
    var safeLocale = me.props.locale || 'zh-cn';
    if (['zh-cn', 'en', 'en-us'].indexOf(safeLocale) === -1) {
      safeLocale = 'zh-cn';
    }
 
    var loadingView = _react2['default'].createElement('div', { className: 'kuma-loading-s kuma-select-uxform-options-loading' });
 
    if (mode === _uxcoreConst2['default'].MODE.EDIT) {
      var options = {
        ref: function ref(c) {
          _this4.select = c;
        },
        key: 'select',
        style: me.props.jsxstyle,
        multiple: me.props.jsxmultiple,
        allowClear: me.props.jsxallowClear,
        combobox: me.props.jsxcombobox,
        searchPlaceholder: me.props.jsxsearchPlaceholder,
        tags: me.props.jsxtags,
        disabled: !!me.props.jsxdisabled,
        showSearch: me.props.jsxshowSearch,
        placeholder: me.props.jsxplaceholder || defaultLabels.placeholder[safeLocale],
        onChange: me.handleChange.bind(me),
        onSearch: me.handleSearch.bind(me),
        onSelect: function onSelect() {
          Iif (_this4.props.onSelect) {
            var _props3;
 
            (_props3 = _this4.props).onSelect.apply(_props3, arguments);
          }
        },
        size: me.getSize()
      };
 
      if (me.props.jsxfetchUrl) {
        options.filterOption = false;
      }
 
      selectOptions.forEach(function (item) {
        if (item in me.props) {
          options[item] = me.props[item];
        }
      });
 
      Eif (!{}.hasOwnProperty.call(me.props, 'notFoundContent')) {
        options.notFoundContent = defaultLabels.notFoundContent[safeLocale];
      }
 
      if (me.state.loading) {
        options.notFoundContent = me.props.loadingView || loadingView;
      }
 
      // only jsxfetchUrl mode need pass label, for the options always change.
      // when mount, state.label is undefined, which cause defalutValue cannot be used.
      if (me.props.jsxfetchUrl || me.props.onSearch) {
        options.labelInValue = true;
      }
 
      options.value = me.processValue() || [];
 
      /* eslint-disable no-underscore-dangle */
      /* used in SearchFormField */
      arr.push(_react2['default'].createElement(
        _uxcoreSelect2['default'],
        options,
        me._generateOptionsFromData()
      ));
      /* eslint-enable no-underscore-dangle */
    } else Eif (mode === _uxcoreConst2['default'].MODE.VIEW) {
      var str = '';
      var renderValues = [];
      var splitter = ', \xA0';
      Eif (me.state.value) {
        var value = me.processValue();
        var values = !Array.isArray(value) ? [value] : value;
        if (me.props.jsxfetchUrl || me.props.onSearch || me.props.labelInValue) {
          // labelInValue mode
          str = values.map(function (item) {
            var label = item.label || item.key;
 
            renderValues.push({
              value: item.key,
              text: label
            });
 
            return label;
          }).join(splitter);
        } else if (me.props.children) {
          // <Option> mode
          var optionsLabel = [];
          me.props.children.forEach(function (child) {
            var valuePropValue = getValuePropValue(child);
            if (values.indexOf(valuePropValue) !== -1) {
              var label = '' + child.props[me.props.optionLabelProp];
 
              optionsLabel.push(label);
 
              renderValues.push({
                value: valuePropValue,
                text: label
              });
            }
          });
 
          str = optionsLabel.length ? optionsLabel.join(splitter) : values.join(splitter);
        } else {
          // only jsxdata
          str = values.map(function (item) {
            var label = transferDataToObj(me.state.data)[item === '' ? '__all__' : item];
 
            renderValues.push({
              value: item,
              text: label || item
            });
 
            return label || item;
          }).join(splitter);
        }
      }
 
      if (me.props.renderView) {
        str = me.props.renderView(renderValues);
      }
 
      arr.push(_react2['default'].createElement(
        'span',
        { key: 'select' },
        str
      ));
    }
    return arr;
  };
 
  return SelectFormField;
}(_uxcoreFormField2['default']);
 
SelectFormField.getDerivedStateFromProps = function (props, state) {
  var baseUpdate = _uxcoreFormField2['default'].getDerivedStateFromProps(props, state);
  var jsxdata = props.jsxdata;
 
  Iif (!(0, _isEqual2['default'])(jsxdata, state.prevPropsData)) {
    return _extends({}, baseUpdate, {
      data: processData(props.jsxdata),
      prevPropsData: props.jsxdata
    });
  }
  return baseUpdate;
};
 
SelectFormField.Option = Option;
SelectFormField.displayName = 'SelectFormField';
SelectFormField.propTypes = (0, _objectAssign2['default'])({}, _uxcoreFormField2['default'].propTypes, {
  jsxstyle: _propTypes2['default'].object,
  jsxplaceholder: _propTypes2['default'].string,
  jsxcombobox: _propTypes2['default'].bool,
  jsxdata: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].array]),
  searchDelay: _propTypes2['default'].number,
  beforeFetch: _propTypes2['default'].func,
  afterFetch: _propTypes2['default'].func,
  jsxshowSearch: _propTypes2['default'].bool,
  jsxtags: _propTypes2['default'].bool,
  jsxmultiple: _propTypes2['default'].bool,
  jsxallowClear: _propTypes2['default'].bool,
  jsxsearchPlaceholder: _propTypes2['default'].string,
  optionFilterProp: _propTypes2['default'].string,
  dataType: _propTypes2['default'].string,
  fetchDataOnMount: _propTypes2['default'].bool,
  useValueText: _propTypes2['default'].bool,
  method: _propTypes2['default'].string,
  dropdownAlign: _propTypes2['default'].object,
  optionTextRender: _propTypes2['default'].func,
  renderView: _propTypes2['default'].func,
  loadingView: _propTypes2['default'].node
});
 
SelectFormField.defaultProps = (0, _objectAssign2['default'])({}, _uxcoreFormField2['default'].defaultProps, {
  jsxstyle: {},
  jsxplaceholder: undefined,
  jsxcombobox: false,
  jsxdata: {},
  searchDelay: 100,
  beforeFetch: function beforeFetch(obj) {
    return obj;
  },
  afterFetch: function afterFetch(obj) {
    return obj;
  },
  fitResponse: function fitResponse(response) {
    return {
      content: response.content || response,
      success: response.success === undefined ? true : response.success
    };
  },
  jsxshowSearch: true,
  jsxallowClear: false,
  jsxtags: false,
  jsxmultiple: false,
  jsxsearchPlaceholder: '',
  optionFilterProp: 'children',
  optionLabelProp: 'children',
  fetchDataOnMount: true,
  useValueText: false,
  method: 'GET',
  dropdownAlign: {
    points: ['tl', 'bl', 'tr', 'br'],
    offset: [0, 4],
    overflow: {
      adjustX: true,
      adjustY: true
    }
  },
  optionTextRender: function optionTextRender(text) {
    return text;
  },
  renderView: undefined,
  loadingView: undefined
});
 
exports['default'] = SelectFormField;
module.exports = exports['default'];