useOptions.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. var _typeof = require("@babel/runtime/helpers/typeof");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = void 0;
  7. var React = _interopRequireWildcard(require("react"));
  8. var _legacyUtil = require("../utils/legacyUtil");
  9. function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
  10. function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
  11. /**
  12. * Parse `children` to `options` if `options` is not provided.
  13. * Then flatten the `options`.
  14. */
  15. var useOptions = function useOptions(options, children, fieldNames, optionFilterProp, optionLabelProp) {
  16. return React.useMemo(function () {
  17. var mergedOptions = options;
  18. var childrenAsData = !options;
  19. if (childrenAsData) {
  20. mergedOptions = (0, _legacyUtil.convertChildrenToData)(children);
  21. }
  22. var valueOptions = new Map();
  23. var labelOptions = new Map();
  24. var setLabelOptions = function setLabelOptions(labelOptionsMap, option, key) {
  25. if (key && typeof key === 'string') {
  26. labelOptionsMap.set(option[key], option);
  27. }
  28. };
  29. var dig = function dig(optionList) {
  30. var isChildren = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  31. // for loop to speed up collection speed
  32. for (var i = 0; i < optionList.length; i += 1) {
  33. var option = optionList[i];
  34. if (!option[fieldNames.options] || isChildren) {
  35. valueOptions.set(option[fieldNames.value], option);
  36. setLabelOptions(labelOptions, option, fieldNames.label);
  37. // https://github.com/ant-design/ant-design/issues/35304
  38. setLabelOptions(labelOptions, option, optionFilterProp);
  39. setLabelOptions(labelOptions, option, optionLabelProp);
  40. } else {
  41. dig(option[fieldNames.options], true);
  42. }
  43. }
  44. };
  45. dig(mergedOptions);
  46. return {
  47. options: mergedOptions,
  48. valueOptions: valueOptions,
  49. labelOptions: labelOptions
  50. };
  51. }, [options, children, fieldNames, optionFilterProp, optionLabelProp]);
  52. };
  53. var _default = exports.default = useOptions;