Liferay.Loader.define("portal-search-web@5.0.90/js/components/SelectVocabularies", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/alert', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/loading-indicator', 'frontend-js-react-web$classnames', 'frontend-js-web', 'frontend-js-react-web$react', './TreeView'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _alert = _interopRequireDefault(require("@frontend-taglib-clay$clayui/alert"));

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _form = require("@frontend-taglib-clay$clayui/form");

    var _icon = _interopRequireDefault(require("@frontend-taglib-clay$clayui/icon"));

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

    var _frontendJsWeb = require("frontend-js-web");

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _TreeView = _interopRequireDefault(require("./TreeView"));

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var CONFIGURATION = {
      headers: new Headers({
        Accept: 'application/json',
        'Accept-Language': Liferay.ThemeDisplay.getBCP47LanguageId(),
        'Content-Type': 'application/json'
      }),
      method: 'GET'
    };
    var SELECT_OPTIONS = {
      ALL: '',
      //  When 'vocabularyIds' is equal to this, 'All Vocabularies' has been selected.
      SELECT: 'SELECT'
    };
    /**
     * Converts a stringified list of IDs into an array of numbers. This separates
     * values by commas, filters out empty values, and parses the string into a
     * number, if possible.
     * @param {string} idsString The list of IDs as a string
     * @return {Array} Array of ID numbers
     */

    var convertToIDArray = function convertToIDArray(idsString) {
      return idsString.split(',').filter(function (id) {
        return id !== '';
      }).map(function (id) {
        try {
          return JSON.parse(id);
        } catch (_unused) {
          return id;
        }
      });
    };

    function SiteRow(_ref) {
      var disabled = _ref.disabled,
          name = _ref.name,
          onSelect = _ref.onSelect,
          vocabularies = _ref.vocabularies;

      var _handleSelect = function _handleSelect() {
        var select = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
        return function (event) {
          event.preventDefault();
          event.stopPropagation();
          onSelect(vocabularies, select);
        };
      };

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "autofit-row"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "autofit-col"
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          className: "component-expander",
          "data-toggle": "collapse",
          displayType: "unstyled",
          monospaced: true,
          tabIndex: "-1"
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: "c-inner",
          tabIndex: "-2"
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          className: "component-expanded-d-inline",
          symbol: "angle-down"
        }), /*#__PURE__*/_react.default.createElement(_icon.default, {
          className: "component-expanded-d-none",
          symbol: "angle-right"
        })))), /*#__PURE__*/_react.default.createElement("div", {
          className: "autofit-col"
        }, name), /*#__PURE__*/_react.default.createElement("div", {
          className: "autofit-col autofit-col-expand"
        }), !!vocabularies.length && !disabled && /*#__PURE__*/_react.default.createElement("div", {
          className: "autofit-col"
        }, /*#__PURE__*/_react.default.createElement(_button.default.Group, {
          spaced: true
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          className: "quick-action-item",
          displayType: "secondary",
          onClick: _handleSelect(),
          small: true
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: "c-inner",
          tabIndex: "-2"
        }, Liferay.Language.get('select-all'))), /*#__PURE__*/_react.default.createElement(_button.default, {
          className: "quick-action-item",
          displayType: "secondary",
          onClick: _handleSelect(false),
          small: true
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: "c-inner",
          tabIndex: "-2"
        }, Liferay.Language.get('deselect-all'))))))
      );
    }

    function VocabularyTree(_ref2) {
      var disabled = _ref2.disabled,
          loading = _ref2.loading,
          selectedKeys = _ref2.selectedKeys,
          setSelectedKeys = _ref2.setSelectedKeys,
          vocabularyTree = _ref2.vocabularyTree;

      var _handleSelect = function _handleSelect(list) {
        var add = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
        var newList = new Set(selectedKeys);
        list.forEach(function (_ref3) {
          var id = _ref3.id;

          if (add) {
            newList.add(id);
          } else {
            newList.delete(id);
          }
        });
        setSelectedKeys(newList);
      };

      var _handleToggle = function _handleToggle(id) {
        return function () {
          _handleSelect([{
            id: id
          }], !selectedKeys.has(id));
        };
      };

      if (loading || vocabularyTree === null) {
        return (/*#__PURE__*/_react.default.createElement(_loadingIndicator.default, {
            size: "sm"
          })
        );
      }

      return vocabularyTree.length ? /*#__PURE__*/_react.default.createElement(_TreeView.default, {
        defaultItems: vocabularyTree
      }, function (item) {
        var _item$children;

        return (/*#__PURE__*/_react.default.createElement(_TreeView.default.Panel, {
            key: item.id,
            trigger: /*#__PURE__*/_react.default.createElement(SiteRow, {
              disabled: disabled,
              itemId: item.id,
              name: item.name || item.descriptiveName,
              onSelect: _handleSelect,
              vocabularies: item.children
            })
          }, ((_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) ? /*#__PURE__*/_react.default.createElement(_TreeView.default.Group, {
            items: item.children
          }, function (_ref4) {
            var id = _ref4.id,
                name = _ref4.name;
            return (/*#__PURE__*/_react.default.createElement(_TreeView.default.Item, {
                key: id
              }, /*#__PURE__*/_react.default.createElement(_form.ClayCheckbox, {
                "aria-label": name,
                checked: selectedKeys.has(id),
                disabled: disabled,
                onChange: _handleToggle(id)
              }), /*#__PURE__*/_react.default.createElement("span", {
                style: {
                  marginLeft: '2px'
                }
              }, name))
            );
          }) : /*#__PURE__*/_react.default.createElement(_TreeView.default.Group, null, /*#__PURE__*/_react.default.createElement(_TreeView.default.Item, null, Liferay.Language.get('no-vocabularies'))))
        );
      }) : /*#__PURE__*/_react.default.createElement("span", {
        className: "text-3 text-secondary"
      }, Liferay.Language.get('an-error-has-occurred-and-we-were-unable-to-load-the-results'));
    }

    function SelectVocabularies(_ref5) {
      var _ref5$disabled = _ref5.disabled,
          disabled = _ref5$disabled === void 0 ? false : _ref5$disabled,
          _ref5$initialSelected = _ref5.initialSelectedVocabularyIds,
          initialSelectedVocabularyIds = _ref5$initialSelected === void 0 ? SELECT_OPTIONS.ALL : _ref5$initialSelected,
          _ref5$namespace = _ref5.namespace,
          namespace = _ref5$namespace === void 0 ? '' : _ref5$namespace,
          _ref5$vocabularyIdsIn = _ref5.vocabularyIdsInputName,
          vocabularyIdsInputName = _ref5$vocabularyIdsIn === void 0 ? '' : _ref5$vocabularyIdsIn;
      var initialSelectedIdsRef = (0, _react.useRef)(new Set(initialSelectedVocabularyIds === SELECT_OPTIONS.ALL ? [] : convertToIDArray(initialSelectedVocabularyIds)));

      var _useState = (0, _react.useState)(initialSelectedVocabularyIds === SELECT_OPTIONS.ALL ? SELECT_OPTIONS.ALL : SELECT_OPTIONS.SELECT),
          _useState2 = _slicedToArray(_useState, 2),
          selection = _useState2[0],
          setSelection = _useState2[1];

      var _useState3 = (0, _react.useState)(initialSelectedIdsRef.current),
          _useState4 = _slicedToArray(_useState3, 2),
          selectedKeys = _useState4[0],
          setSelectedKeys = _useState4[1];

      var _useState5 = (0, _react.useState)(null),
          _useState6 = _slicedToArray(_useState5, 2),
          vocabularyTree = _useState6[0],
          setVocabularyTree = _useState6[1];

      var _useState7 = (0, _react.useState)([]),
          _useState8 = _slicedToArray(_useState7, 2),
          vocabularyTreeIds = _useState8[0],
          setVocabularyTreeIds = _useState8[1];

      var _useState9 = (0, _react.useState)(false),
          _useState10 = _slicedToArray(_useState9, 2),
          vocabularyTreeLoading = _useState10[0],
          setVocabularyTreeLoading = _useState10[1];

      var _handleFetchVocabularyTree = function _handleFetchVocabularyTree() {
        setVocabularyTreeLoading(true);
        (0, _frontendJsWeb.fetch)('/o/headless-admin-user/v1.0/my-user-account', CONFIGURATION).then(function (response) {
          return response.json();
        }).then(function (_ref6) {
          var siteBriefs = _ref6.siteBriefs;
          Promise.all(siteBriefs.map(function (site) {
            return (0, _frontendJsWeb.fetch)("/o/headless-admin-taxonomy/v1.0/sites/".concat(site.id, "/taxonomy-vocabularies"), CONFIGURATION).then(function (response) {
              return response.json();
            });
          })).then(function (response) {
            var ids = [];
            setVocabularyTree(response.map(function (vocabularies, index) {
              return _objectSpread(_objectSpread({}, siteBriefs[index]), {}, {
                children: ((vocabularies === null || vocabularies === void 0 ? void 0 : vocabularies.items) || []).map(function (_ref7) {
                  var id = _ref7.id,
                      name = _ref7.name;
                  ids.push(id); // Collect IDs for _isDisplayInfoSelectedVocabulariesHidden

                  return {
                    id: id,
                    name: name
                  };
                })
              });
            }));
            setVocabularyTreeIds(ids);
          }).catch(function () {
            return setVocabularyTree([]);
          });
        }).catch(function () {
          return setVocabularyTree([]);
        }).finally(function () {
          return setVocabularyTreeLoading(false);
        });
      };

      (0, _react.useEffect)(function () {
        if (selection === SELECT_OPTIONS.SELECT) {
          _handleFetchVocabularyTree();
        }
      }, []); //eslint-disable-line

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('select-vocabularies', {
            disabled: disabled
          })
        }, /*#__PURE__*/_react.default.createElement("label", {
          className: (0, _classnames.default)({
            disabled: disabled
          })
        }, Liferay.Language.get('select-vocabularies')), /*#__PURE__*/_react.default.createElement("input", {
          hidden: true,
          id: "".concat(namespace).concat(vocabularyIdsInputName),
          name: "".concat(namespace).concat(vocabularyIdsInputName),
          readOnly: true,
          value: selection === SELECT_OPTIONS.ALL ? SELECT_OPTIONS.ALL : Array.from(selectedKeys).toString()
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "select-vocabularies-helptext text-3"
        }, disabled ? Liferay.Language.get('select-vocabularies-configuration-description') : /*#__PURE__*/_react.default.createElement("div", null, Liferay.Language.get('select-vocabularies-configuration-enabled-description'))), /*#__PURE__*/_react.default.createElement(_form.ClayRadioGroup, {
          onSelectedValueChange: function _handleSelectionChange(value) {
            setSelection(value);

            if (value === SELECT_OPTIONS.SELECT && !vocabularyTree) {
              _handleFetchVocabularyTree();
            }
          },
          selectedValue: selection
        }, /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          disabled: disabled,
          label: Liferay.Language.get('all-vocabularies'),
          value: SELECT_OPTIONS.ALL
        }), /*#__PURE__*/_react.default.createElement(_form.ClayRadio, {
          disabled: disabled,
          label: Liferay.Language.get('select-vocabularies'),
          value: SELECT_OPTIONS.SELECT
        })), selection === SELECT_OPTIONS.SELECT && function _isDisplayInfoSelectedVocabulariesHidden() {
          return Array.from(initialSelectedIdsRef.current).some(function (id) {
            return !vocabularyTreeIds.includes(id);
          });
        }() && /*#__PURE__*/_react.default.createElement(_alert.default, {
          displayType: "info",
          title: "".concat(Liferay.Language.get('info'), ":")
        }, Liferay.Language.get('select-vocabularies-configuration-view-permission-alert')), selection === SELECT_OPTIONS.SELECT && /*#__PURE__*/_react.default.createElement(VocabularyTree, {
          disabled: disabled,
          loading: vocabularyTreeLoading,
          selectedKeys: selectedKeys,
          setSelectedKeys: setSelectedKeys,
          vocabularyTree: vocabularyTree
        }))
      );
    }

    var _default = SelectVocabularies;
    exports.default = _default;
    //# sourceMappingURL=SelectVocabularies.js.map
  }
});
//# sourceMappingURL=SelectVocabularies.js.map