"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _isUndefined2 = _interopRequireDefault(require("lodash/isUndefined"));

var _cloneDeep2 = _interopRequireDefault(require("lodash/cloneDeep"));

var _omit2 = _interopRequireDefault(require("lodash/omit"));

var _isFunction2 = _interopRequireDefault(require("lodash/isFunction"));

var _pick2 = _interopRequireDefault(require("lodash/pick"));

var _isNil2 = _interopRequireDefault(require("lodash/isNil"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _VirtualizedList = require("../Picker/VirtualizedList");

var _CheckTreeNode = _interopRequireDefault(require("./CheckTreeNode"));

var _utils = require("../utils");

var _Picker = require("../Picker");

var _utils2 = require("./utils");

var _treeUtils = require("../utils/treeUtils");

var _TreePicker = require("../TreePicker/TreePicker");

var defaultProps = (0, _extends2.default)({}, _Picker.listPickerDefaultProps, {
  as: 'div',
  height: 360,
  cascade: true,
  countable: true,
  searchable: true,
  menuAutoWidth: true,
  defaultValue: [],
  appearance: 'default',
  uncheckableItemValues: [],
  classPrefix: 'picker',
  placement: 'bottomStart'
});

var CheckTreePicker = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
  var Component = props.as,
      data = props.data,
      style = props.style,
      cleanable = props.cleanable,
      countable = props.countable,
      searchBy = props.searchBy,
      toggleAs = props.toggleAs,
      searchKeyword = props.searchKeyword,
      overrideLocale = props.locale,
      inline = props.inline,
      cascade = props.cascade,
      disabled = props.disabled,
      valueKey = props.valueKey,
      labelKey = props.labelKey,
      placement = props.placement,
      childrenKey = props.childrenKey,
      placeholder = props.placeholder,
      controlledValue = props.value,
      defaultValue = props.defaultValue,
      defaultExpandAll = props.defaultExpandAll,
      disabledItemValues = props.disabledItemValues,
      controlledExpandItemValues = props.expandItemValues,
      defaultExpandItemValues = props.defaultExpandItemValues,
      height = props.height,
      menuStyle = props.menuStyle,
      searchable = props.searchable,
      virtualized = props.virtualized,
      className = props.className,
      classPrefix = props.classPrefix,
      menuClassName = props.menuClassName,
      menuAutoWidth = props.menuAutoWidth,
      uncheckableItemValues = props.uncheckableItemValues,
      id = props.id,
      renderMenu = props.renderMenu,
      getChildren = props.getChildren,
      renderExtraFooter = props.renderExtraFooter,
      onEntered = props.onEntered,
      onChange = props.onChange,
      onClean = props.onClean,
      onClose = props.onClose,
      onExited = props.onExited,
      onSearch = props.onSearch,
      onSelect = props.onSelect,
      onOpen = props.onOpen,
      onScroll = props.onScroll,
      onExpand = props.onExpand,
      renderValue = props.renderValue,
      renderTreeIcon = props.renderTreeIcon,
      renderTreeNode = props.renderTreeNode,
      rest = (0, _objectWithoutPropertiesLoose2.default)(props, ["as", "data", "style", "cleanable", "countable", "searchBy", "toggleAs", "searchKeyword", "locale", "inline", "cascade", "disabled", "valueKey", "labelKey", "placement", "childrenKey", "placeholder", "value", "defaultValue", "defaultExpandAll", "disabledItemValues", "expandItemValues", "defaultExpandItemValues", "height", "menuStyle", "searchable", "virtualized", "className", "classPrefix", "menuClassName", "menuAutoWidth", "uncheckableItemValues", "id", "renderMenu", "getChildren", "renderExtraFooter", "onEntered", "onChange", "onClean", "onClose", "onExited", "onSearch", "onSelect", "onOpen", "onScroll", "onExpand", "renderValue", "renderTreeIcon", "renderTreeNode"]);
  var triggerRef = (0, _react.useRef)();
  var targetRef = (0, _react.useRef)();
  var listRef = (0, _react.useRef)();
  var overlayRef = (0, _react.useRef)();
  var searchInputRef = (0, _react.useRef)();
  var treeViewRef = (0, _react.useRef)();

  var _useCustom = (0, _utils.useCustom)('Picker', overrideLocale),
      rtl = _useCustom.rtl,
      locale = _useCustom.locale;

  var _useState = (0, _react.useState)(false),
      active = _useState[0],
      setActive = _useState[1];

  var _useState2 = (0, _react.useState)(null),
      activeNode = _useState2[0],
      setActiveNode = _useState2[1];

  var _useClassNames = (0, _utils.useClassNames)(classPrefix),
      prefix = _useClassNames.prefix,
      merge = _useClassNames.merge;

  var _useClassNames2 = (0, _utils.useClassNames)('check-tree'),
      checkTreePrefix = _useClassNames2.prefix,
      withCheckTreeClassPrefix = _useClassNames2.withClassPrefix;

  var _useControlled = (0, _utils.useControlled)(controlledValue, defaultValue),
      value = _useControlled[0],
      setValue = _useControlled[1],
      isControlled = _useControlled[2];

  var _useGetTreeNodeChildr = (0, _treeUtils.useGetTreeNodeChildren)(data, valueKey, childrenKey),
      treeData = _useGetTreeNodeChildr.data,
      setTreeData = _useGetTreeNodeChildr.setData,
      loadingNodeValues = _useGetTreeNodeChildr.loadingNodeValues,
      loadChildren = _useGetTreeNodeChildr.loadChildren;

  var _useControlled2 = (0, _utils.useControlled)(controlledExpandItemValues, (0, _treeUtils.getDefaultExpandItemValues)(treeData, {
    defaultExpandAll: defaultExpandAll,
    valueKey: valueKey,
    childrenKey: childrenKey,
    defaultExpandItemValues: defaultExpandItemValues
  })),
      expandItemValues = _useControlled2[0],
      setExpandItemValues = _useControlled2[1];

  var _useState3 = (0, _react.useState)(null),
      focusItemValue = _useState3[0],
      setFocusItemValue = _useState3[1];

  var _useFlattenTreeData = (0, _treeUtils.useFlattenTreeData)({
    data: treeData,
    labelKey: labelKey,
    valueKey: valueKey,
    childrenKey: childrenKey,
    uncheckableItemValues: uncheckableItemValues,
    callback: function callback(nodes) {
      // after flattenData, always unSerialize check property value
      unSerializeList({
        nodes: nodes,
        key: 'check',
        value: value,
        cascade: cascade,
        uncheckableItemValues: uncheckableItemValues
      });
      forceUpdate();
    }
  }),
      flattenNodes = _useFlattenTreeData.flattenNodes,
      forceUpdate = _useFlattenTreeData.forceUpdate,
      formatVirtualizedTreeData = _useFlattenTreeData.formatVirtualizedTreeData,
      serializeListOnlyParent = _useFlattenTreeData.serializeListOnlyParent,
      unSerializeList = _useFlattenTreeData.unSerializeList;

  var _useTreeSearch = (0, _treeUtils.useTreeSearch)({
    labelKey: labelKey,
    childrenKey: childrenKey,
    searchKeyword: searchKeyword,
    data: treeData,
    searchBy: searchBy,
    callback: function callback(searchKeyword, _filterData, event) {
      onSearch === null || onSearch === void 0 ? void 0 : onSearch(searchKeyword, event);
    }
  }),
      filteredData = _useTreeSearch.filteredData,
      searchKeywordState = _useTreeSearch.searchKeywordState,
      setSearchKeyword = _useTreeSearch.setSearchKeyword,
      handleSearch = _useTreeSearch.handleSearch,
      setFilteredData = _useTreeSearch.setFilteredData;

  var _useTreeNodeRefs = (0, _treeUtils.useTreeNodeRefs)(),
      treeNodesRefs = _useTreeNodeRefs.treeNodesRefs,
      saveTreeNodeRef = _useTreeNodeRefs.saveTreeNodeRef;
  /**
   * get formatted nodes for render tree
   * @params render - renderNode function. only used when virtualized setting false
   */


  var getFormattedNodes = (0, _react.useCallback)(function (render) {
    var formattedNodes = [];

    if (virtualized) {
      formattedNodes = formatVirtualizedTreeData(flattenNodes, filteredData, expandItemValues, {
        cascade: cascade,
        searchKeyword: searchKeywordState
      }).filter(function (item) {
        return item.visible;
      });
    } else {
      formattedNodes = (0, _utils2.getFormattedTree)(filteredData, flattenNodes, {
        childrenKey: childrenKey,
        cascade: cascade
      }).map(function (node) {
        return render === null || render === void 0 ? void 0 : render(node, 1);
      });
    }

    return formattedNodes;
  }, [searchKeywordState, expandItemValues, filteredData, flattenNodes, formatVirtualizedTreeData, virtualized, childrenKey, cascade]);

  var getTreeNodeProps = function getTreeNodeProps(node, layer) {
    return {
      as: Component,
      rtl: rtl,
      value: node[valueKey],
      label: node[labelKey],
      layer: layer,
      focus: (0, _utils.shallowEqual)(focusItemValue, node[valueKey]),
      expand: node.expand,
      visible: node.visible,
      loading: loadingNodeValues.some(function (item) {
        return (0, _utils.shallowEqual)(item, node[valueKey]);
      }),
      disabled: (0, _utils2.getDisabledState)(flattenNodes, node, {
        disabledItemValues: disabledItemValues,
        valueKey: valueKey
      }),
      nodeData: node,
      checkState: node.checkState,
      uncheckable: (0, _utils2.isNodeUncheckable)(node, {
        uncheckableItemValues: uncheckableItemValues,
        valueKey: valueKey
      }),
      allUncheckable: (0, _utils2.isAllSiblingNodeUncheckable)(node, flattenNodes, uncheckableItemValues, valueKey),
      onSelect: handleSelect,
      onExpand: handleExpand,
      onRenderTreeNode: renderTreeNode,
      onRenderTreeIcon: renderTreeIcon
    };
  };

  var focusActiveNode = (0, _react.useCallback)(function () {
    (0, _treeUtils.focusToActiveTreeNode)({
      list: listRef.current,
      valueKey: valueKey,
      selector: "." + checkTreePrefix('node-active'),
      activeNode: activeNode,
      virtualized: virtualized,
      container: treeViewRef.current,
      formattedNodes: getFormattedNodes()
    });
  }, [checkTreePrefix, activeNode, getFormattedNodes, valueKey, virtualized]);
  (0, _react.useEffect)(function () {
    setValue((0, _utils2.getCheckTreePickerDefaultValue)(value, uncheckableItemValues));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  (0, _react.useEffect)(function () {
    setFilteredData(data, searchKeywordState);
    setTreeData(data);
  }, [data, searchKeywordState, setFilteredData, setTreeData]);
  (0, _react.useEffect)(function () {
    setFilteredData(treeData, searchKeywordState);
  }, [treeData, searchKeywordState, setFilteredData]);
  (0, _react.useEffect)(function () {
    if (Array.isArray(controlledExpandItemValues)) {
      setExpandItemValues(controlledExpandItemValues);
    }
  }, [controlledExpandItemValues, setExpandItemValues]);
  (0, _react.useEffect)(function () {
    setSearchKeyword(searchKeyword !== null && searchKeyword !== void 0 ? searchKeyword : '');
  }, [searchKeyword, setSearchKeyword]);
  (0, _react.useEffect)(function () {
    unSerializeList({
      nodes: flattenNodes,
      key: 'check',
      value: value,
      cascade: cascade,
      uncheckableItemValues: uncheckableItemValues
    });
    forceUpdate();
  }, [cascade, value, uncheckableItemValues, unSerializeList, flattenNodes, forceUpdate]);
  var toggleUpChecked = (0, _react.useCallback)(function (nodes, node, checked) {
    var currentNode = nodes[node.refKey];

    if (cascade) {
      if (!checked) {
        currentNode.check = checked;
        currentNode.checkAll = checked;
      } else {
        if ((0, _utils2.isEveryChildChecked)(nodes, currentNode)) {
          currentNode.check = true;
          currentNode.checkAll = true;
        } else {
          currentNode.check = false;
          currentNode.checkAll = false;
        }
      }

      if (currentNode.parent) {
        toggleUpChecked(nodes, currentNode.parent, checked);
      }
    }
  }, [cascade]);
  var toggleDownChecked = (0, _react.useCallback)(function (nodes, node, isChecked) {
    var currentNode = nodes[node.refKey];
    currentNode.check = isChecked;

    if (!currentNode[childrenKey] || !currentNode[childrenKey].length || !cascade) {
      currentNode.checkAll = false;
    } else {
      currentNode.checkAll = isChecked;
      currentNode[childrenKey].forEach(function (child) {
        toggleDownChecked(nodes, child, isChecked);
      });
    }
  }, [cascade, childrenKey]);
  var toggleChecked = (0, _react.useCallback)(function (node, isChecked) {
    var nodes = (0, _cloneDeep2.default)(flattenNodes);
    toggleDownChecked(nodes, node, isChecked);
    node.parent && toggleUpChecked(nodes, node.parent, isChecked);
    var values = serializeListOnlyParent(nodes, 'check'); // filter uncheckableItemValues

    return values.filter(function (v) {
      return !uncheckableItemValues.includes(v);
    });
  }, [flattenNodes, uncheckableItemValues, serializeListOnlyParent, toggleDownChecked, toggleUpChecked]);
  var handleSelect = (0, _react.useCallback)(function (node, event) {
    if (!node) {
      return;
    }

    var selectedValues = toggleChecked(node, !flattenNodes[node.refKey].check);

    if (!isControlled) {
      unSerializeList({
        nodes: flattenNodes,
        key: 'check',
        value: selectedValues,
        cascade: cascade,
        uncheckableItemValues: uncheckableItemValues
      });
      setValue(selectedValues);
    }

    setActiveNode(node);
    setFocusItemValue(node[valueKey]);
    onChange === null || onChange === void 0 ? void 0 : onChange(selectedValues, event);
    onSelect === null || onSelect === void 0 ? void 0 : onSelect(node, selectedValues, event);
  }, [cascade, valueKey, flattenNodes, isControlled, uncheckableItemValues, setValue, onChange, onSelect, toggleChecked, unSerializeList]);

  var hasValue = function hasValue() {
    var selectedValues = Object.keys(flattenNodes).map(function (refKey) {
      return flattenNodes[refKey][valueKey];
    }).filter(function (item) {
      return value.some(function (v) {
        return (0, _utils.shallowEqual)(v, item);
      });
    });
    return !!selectedValues.length;
  };

  var handleOpen = (0, _react.useCallback)(function () {
    var _triggerRef$current, _triggerRef$current$o;

    (_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 ? void 0 : (_triggerRef$current$o = _triggerRef$current.open) === null || _triggerRef$current$o === void 0 ? void 0 : _triggerRef$current$o.call(_triggerRef$current);
    setFocusItemValue(activeNode === null || activeNode === void 0 ? void 0 : activeNode[valueKey]);
    focusActiveNode();
    onOpen === null || onOpen === void 0 ? void 0 : onOpen();
    setActive(true);
  }, [activeNode, focusActiveNode, onOpen, valueKey]);
  var handleClose = (0, _react.useCallback)(function () {
    var _triggerRef$current2, _triggerRef$current2$, _targetRef$current;

    (_triggerRef$current2 = triggerRef.current) === null || _triggerRef$current2 === void 0 ? void 0 : (_triggerRef$current2$ = _triggerRef$current2.close) === null || _triggerRef$current2$ === void 0 ? void 0 : _triggerRef$current2$.call(_triggerRef$current2);
    setSearchKeyword('');
    onClose === null || onClose === void 0 ? void 0 : onClose();
    setFocusItemValue(null);
    setActive(false);
    /**
     * when using keyboard toggle picker, should refocus on PickerToggle Component after close picker menu
     */

    (_targetRef$current = targetRef.current) === null || _targetRef$current === void 0 ? void 0 : _targetRef$current.focus();
  }, [onClose, setSearchKeyword]);
  var handleExpand = (0, _react.useCallback)(function (node) {
    var nextExpandItemValues = (0, _treeUtils.toggleExpand)({
      node: node,
      isExpand: !node.expand,
      expandItemValues: expandItemValues,
      valueKey: valueKey
    });
    setExpandItemValues(nextExpandItemValues);
    onExpand === null || onExpand === void 0 ? void 0 : onExpand(nextExpandItemValues, node, (0, _Picker.createConcatChildrenFunction)(node, node[valueKey], {
      valueKey: valueKey,
      childrenKey: childrenKey
    }));

    if ((0, _isFunction2.default)(getChildren) && !node.expand && Array.isArray(node[childrenKey]) && node[childrenKey].length === 0) {
      loadChildren(node, getChildren);
    }
  }, [childrenKey, expandItemValues, getChildren, loadChildren, onExpand, setExpandItemValues, valueKey]);
  (0, _Picker.usePublicMethods)(ref, {
    triggerRef: triggerRef,
    overlayRef: overlayRef,
    targetRef: targetRef
  });
  var handleClean = (0, _react.useCallback)(function (event) {
    var target = event.target; // exclude searchBar

    if (target.matches('div[role="searchbox"] > input')) {
      return;
    }

    setActiveNode(null);
    setValue([]);
    setFocusItemValue(null);
    unSerializeList({
      nodes: flattenNodes,
      key: 'check',
      value: [],
      cascade: cascade,
      uncheckableItemValues: uncheckableItemValues
    });
    onChange === null || onChange === void 0 ? void 0 : onChange([], event);
  }, [cascade, flattenNodes, onChange, setValue, unSerializeList, uncheckableItemValues]);
  var handleFocusItem = (0, _react.useCallback)(function (key) {
    var focusableItems = (0, _treeUtils.getFocusableItems)(filteredData, {
      disabledItemValues: disabledItemValues,
      valueKey: valueKey,
      childrenKey: childrenKey,
      expandItemValues: expandItemValues
    }, (0, _treeUtils.isSearching)(searchKeywordState));
    var selector = "." + checkTreePrefix('node-label');
    var focusProps = {
      focusItemValue: focusItemValue,
      focusableItems: focusableItems,
      treeNodesRefs: treeNodesRefs,
      selector: selector,
      valueKey: valueKey,
      callback: function callback(nextFocusItemValue) {
        setFocusItemValue(nextFocusItemValue);
      }
    };

    if (key === _utils.KEY_VALUES.DOWN) {
      (0, _treeUtils.focusNextItem)(focusProps);
      return;
    }

    if (key === _utils.KEY_VALUES.UP) {
      (0, _treeUtils.focusPreviousItem)(focusProps);
    }
  }, [searchKeywordState, checkTreePrefix, expandItemValues, filteredData, focusItemValue, treeNodesRefs, childrenKey, valueKey, disabledItemValues]);
  var handleLeftArrow = (0, _react.useCallback)(function () {
    var focusItem = (0, _treeUtils.getActiveItem)(focusItemValue, flattenNodes, valueKey);
    (0, _treeUtils.leftArrowHandler)({
      focusItem: focusItem,
      expand: expandItemValues.includes(focusItem === null || focusItem === void 0 ? void 0 : focusItem[valueKey]),
      onExpand: handleExpand,
      onFocusItem: function onFocusItem() {
        var _focusItem$parent, _focusItem$parent2;

        setFocusItemValue(focusItem === null || focusItem === void 0 ? void 0 : (_focusItem$parent = focusItem.parent) === null || _focusItem$parent === void 0 ? void 0 : _focusItem$parent[valueKey]);
        (0, _treeUtils.focusTreeNode)(focusItem === null || focusItem === void 0 ? void 0 : (_focusItem$parent2 = focusItem.parent) === null || _focusItem$parent2 === void 0 ? void 0 : _focusItem$parent2.refKey, treeNodesRefs, "." + checkTreePrefix('node-label'));
      }
    });
  }, [checkTreePrefix, expandItemValues, flattenNodes, focusItemValue, handleExpand, treeNodesRefs, valueKey]);
  var handleRightArrow = (0, _react.useCallback)(function () {
    var focusItem = (0, _treeUtils.getActiveItem)(focusItemValue, flattenNodes, valueKey);
    (0, _treeUtils.rightArrowHandler)({
      focusItem: focusItem,
      expand: expandItemValues.includes(focusItem === null || focusItem === void 0 ? void 0 : focusItem[valueKey]),
      childrenKey: childrenKey,
      onExpand: handleExpand,
      onFocusItem: function onFocusItem() {
        handleFocusItem(_utils.KEY_VALUES.DOWN);
      }
    });
  }, [focusItemValue, flattenNodes, valueKey, expandItemValues, childrenKey, handleExpand, handleFocusItem]);
  var selectActiveItem = (0, _react.useCallback)(function (event) {
    var activeItem = (0, _treeUtils.getActiveItem)(focusItemValue, flattenNodes, valueKey);

    if (!(0, _utils2.isNodeUncheckable)(activeItem, {
      uncheckableItemValues: uncheckableItemValues,
      valueKey: valueKey
    }) && activeItem !== null) {
      handleSelect(activeItem, event);
    }
  }, [flattenNodes, focusItemValue, handleSelect, uncheckableItemValues, valueKey]);
  var onPickerKeydown = (0, _Picker.useToggleKeyDownEvent)({
    toggle: !focusItemValue || !active,
    triggerRef: triggerRef,
    targetRef: targetRef,
    overlayRef: overlayRef,
    searchInputRef: searchInputRef,
    active: active,
    onExit: handleClean,
    onClose: handleClose,
    onMenuKeyDown: function onMenuKeyDown(event) {
      (0, _Picker.onMenuKeyDown)(event, {
        down: function down() {
          return handleFocusItem(_utils.KEY_VALUES.DOWN);
        },
        up: function up() {
          return handleFocusItem(_utils.KEY_VALUES.UP);
        },
        left: rtl ? handleRightArrow : handleLeftArrow,
        right: rtl ? handleLeftArrow : handleRightArrow,
        enter: selectActiveItem,
        del: handleClean
      });
    }
  });
  var handleTreeKeydown = (0, _react.useCallback)(function (event) {
    if (!treeViewRef.current) {
      return;
    }

    (0, _Picker.onMenuKeyDown)(event, {
      down: function down() {
        return handleFocusItem(_utils.KEY_VALUES.DOWN);
      },
      up: function up() {
        return handleFocusItem(_utils.KEY_VALUES.UP);
      },
      left: rtl ? handleRightArrow : handleLeftArrow,
      right: rtl ? handleLeftArrow : handleRightArrow,
      enter: selectActiveItem
    });
  }, [handleFocusItem, handleLeftArrow, handleRightArrow, rtl, selectActiveItem]);

  var renderNode = function renderNode(node, layer) {
    var visible = node.visible,
        refKey = node.refKey; // when searching, all nodes should be expand

    var expand = (0, _treeUtils.getExpandWhenSearching)(searchKeywordState, expandItemValues.includes(node[valueKey]));

    if (!visible) {
      return null;
    }

    var children = node[childrenKey];
    var visibleChildren = (0, _isUndefined2.default)(searchKeywordState) || searchKeywordState.length === 0 ? !!children : (0, _treeUtils.hasVisibleChildren)(node, childrenKey);
    var nodeProps = (0, _extends2.default)({}, getTreeNodeProps((0, _extends2.default)({}, node, {
      expand: expand
    }), layer), {
      hasChildren: visibleChildren
    });

    if (nodeProps.hasChildren) {
      var _merge;

      layer += 1;
      var openClass = checkTreePrefix('open');
      var childrenClass = merge(checkTreePrefix('node-children'), (_merge = {}, _merge[openClass] = expand && visibleChildren, _merge));
      var nodes = children || [];
      return /*#__PURE__*/_react.default.createElement("div", {
        className: childrenClass,
        key: node[valueKey]
      }, /*#__PURE__*/_react.default.createElement(_CheckTreeNode.default, (0, _extends2.default)({}, nodeProps, {
        ref: function ref(_ref) {
          return saveTreeNodeRef(refKey, _ref);
        }
      })), /*#__PURE__*/_react.default.createElement("div", {
        className: checkTreePrefix('children')
      }, nodes.map(function (child) {
        return renderNode(child, layer);
      })));
    }

    return /*#__PURE__*/_react.default.createElement(_CheckTreeNode.default, (0, _extends2.default)({
      key: node[valueKey],
      ref: function ref(_ref2) {
        return saveTreeNodeRef(refKey, _ref2);
      }
    }, nodeProps));
  };

  var renderVirtualListNode = function renderVirtualListNode(nodes) {
    return function (_ref3) {
      var key = _ref3.key,
          index = _ref3.index,
          style = _ref3.style;
      var node = nodes[index];
      var layer = node.layer,
          refKey = node.refKey,
          visible = node.visible;
      var expand = (0, _treeUtils.getExpandWhenSearching)(searchKeywordState, expandItemValues.includes(node[valueKey]));
      var nodeProps = (0, _extends2.default)({}, getTreeNodeProps((0, _extends2.default)({}, node, {
        expand: expand
      }), layer), {
        hasChildren: node.hasChildren
      });
      return visible && /*#__PURE__*/_react.default.createElement(_CheckTreeNode.default, (0, _extends2.default)({
        style: style,
        key: key,
        ref: function ref(_ref4) {
          return saveTreeNodeRef(refKey, _ref4);
        }
      }, nodeProps));
    };
  };

  var renderCheckTree = function renderCheckTree() {
    var _withCheckTreeClassPr, _merge2;

    var classes = withCheckTreeClassPrefix((_withCheckTreeClassPr = {}, _withCheckTreeClassPr[className !== null && className !== void 0 ? className : ''] = inline, _withCheckTreeClassPr['without-children'] = !_utils2.isSomeNodeHasChildren, _withCheckTreeClassPr.virtualized = virtualized, _withCheckTreeClassPr));
    var formattedNodes = getFormattedNodes(renderNode);

    if (!formattedNodes.some(function (v) {
      return v !== null;
    })) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: prefix('none')
      }, locale.noResultsText);
    }

    var treeNodesClass = merge(checkTreePrefix('nodes'), (_merge2 = {}, _merge2[checkTreePrefix('all-uncheckable')] = (0, _utils2.isEveryFirstLevelNodeUncheckable)(flattenNodes, uncheckableItemValues, valueKey), _merge2));
    var styles = inline ? (0, _extends2.default)({
      height: height
    }, style) : {};
    return /*#__PURE__*/_react.default.createElement("div", {
      id: id ? id + "-listbox" : undefined,
      ref: treeViewRef,
      role: "tree",
      "aria-multiselectable": true,
      className: classes,
      style: styles,
      onScroll: onScroll,
      onKeyDown: inline ? handleTreeKeydown : undefined
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: treeNodesClass
    }, virtualized ? /*#__PURE__*/_react.default.createElement(_VirtualizedList.AutoSizer, {
      defaultHeight: inline ? height : _TreePicker.maxTreeHeight,
      style: {
        width: 'auto',
        height: 'auto'
      }
    }, function (_ref5) {
      var height = _ref5.height,
          width = _ref5.width;
      return /*#__PURE__*/_react.default.createElement(_VirtualizedList.List, {
        ref: listRef,
        width: width,
        height: height,
        rowHeight: 36,
        rowCount: formattedNodes.length,
        rowRenderer: renderVirtualListNode(formattedNodes),
        scrollToAlignment: "center"
      });
    }) : formattedNodes));
  };

  var renderDropdownMenu = function renderDropdownMenu(positionProps, speakerRef) {
    var left = positionProps.left,
        top = positionProps.top,
        className = positionProps.className;
    var classes = (0, _classnames.default)(className, menuClassName, prefix('check-tree-menu'));
    var mergedMenuStyle = (0, _extends2.default)({}, menuStyle, {
      left: left,
      top: top
    });
    var styles = virtualized ? (0, _extends2.default)({
      height: height
    }, mergedMenuStyle) : (0, _extends2.default)({}, mergedMenuStyle);
    return /*#__PURE__*/_react.default.createElement(_Picker.PickerOverlay, {
      autoWidth: menuAutoWidth,
      className: classes,
      style: styles,
      ref: (0, _utils.mergeRefs)(overlayRef, speakerRef),
      onKeyDown: onPickerKeydown,
      target: triggerRef
    }, searchable ? /*#__PURE__*/_react.default.createElement(_Picker.SearchBar, {
      placeholder: locale.searchPlaceholder,
      onChange: handleSearch,
      value: searchKeywordState,
      inputRef: searchInputRef
    }) : null, renderMenu ? renderMenu(renderCheckTree()) : renderCheckTree(), renderExtraFooter === null || renderExtraFooter === void 0 ? void 0 : renderExtraFooter());
  };
  /**
   * 1.Have a value and the value is valid.
   * 2.Regardless of whether the value is valid, as long as renderValue is set, it is judged to have a value.
   */


  var hasValidValue = hasValue() || value.length > 0 && (0, _isFunction2.default)(renderValue);
  var selectedElement = placeholder;
  var selectedItems = (0, _utils2.getSelectedItems)(flattenNodes, value, valueKey);

  if (hasValidValue) {
    selectedElement = /*#__PURE__*/_react.default.createElement(_Picker.SelectedElement, {
      selectedItems: selectedItems,
      countable: countable,
      valueKey: valueKey,
      labelKey: labelKey,
      childrenKey: childrenKey,
      prefix: prefix,
      cascade: cascade,
      locale: locale
    });

    if ((0, _isFunction2.default)(renderValue)) {
      selectedElement = renderValue(value, selectedItems, selectedElement);

      if ((0, _isNil2.default)(selectedElement)) {
        hasValidValue = false;
      }
    }
  }

  var _usePickerClassName = (0, _Picker.usePickerClassName)((0, _extends2.default)({}, props, {
    hasValue: hasValidValue,
    name: 'check-tree'
  })),
      classes = _usePickerClassName[0],
      usedClassNamePropKeys = _usePickerClassName[1];

  if (inline) {
    return renderCheckTree();
  }

  return /*#__PURE__*/_react.default.createElement(_Picker.PickerToggleTrigger, {
    pickerProps: (0, _pick2.default)(props, _Picker.pickTriggerPropKeys),
    ref: triggerRef,
    placement: placement,
    onEnter: handleOpen,
    onEntered: onEntered,
    onExited: (0, _utils.createChainedFunction)(handleClose, onExited),
    speaker: renderDropdownMenu
  }, /*#__PURE__*/_react.default.createElement(Component, {
    className: classes,
    style: style
  }, /*#__PURE__*/_react.default.createElement(_Picker.PickerToggle, (0, _extends2.default)({}, (0, _omit2.default)(rest, [].concat(_Picker.omitTriggerPropKeys, usedClassNamePropKeys)), {
    id: id,
    ref: targetRef,
    onKeyDown: onPickerKeydown,
    onClean: (0, _utils.createChainedFunction)(handleClean, onClean),
    cleanable: cleanable && !disabled,
    disabled: disabled,
    as: toggleAs,
    hasValue: hasValidValue,
    active: active,
    placement: placement,
    inputValue: value
  }), selectedElement || locale.placeholder)));
});

CheckTreePicker.displayName = 'CheckTreePicker';
CheckTreePicker.defaultProps = defaultProps;
CheckTreePicker.propTypes = (0, _extends2.default)({}, _Picker.listPickerPropTypes, {
  height: _propTypes.default.number,
  appearance: _propTypes.default.oneOf(['default', 'subtle']),
  inline: _propTypes.default.bool,
  locale: _propTypes.default.any,
  cascade: _propTypes.default.bool,
  countable: _propTypes.default.bool,
  searchable: _propTypes.default.bool,
  virtualized: _propTypes.default.bool,
  searchKeyword: _propTypes.default.string,
  menuAutoWidth: _propTypes.default.bool,
  defaultExpandAll: _propTypes.default.bool,
  containerPadding: _propTypes.default.number,
  disabledItemValues: _propTypes.default.array,
  expandItemValues: _propTypes.default.array,
  defaultExpandItemValues: _propTypes.default.array,
  uncheckableItemValues: _propTypes.default.array,
  onSearch: _propTypes.default.func,
  onExpand: _propTypes.default.func,
  onSelect: _propTypes.default.func,
  renderMenu: _propTypes.default.func,
  renderTreeNode: _propTypes.default.func,
  renderTreeIcon: _propTypes.default.func,
  searchBy: _propTypes.default.func,
  onScroll: _propTypes.default.func
});
var _default = CheckTreePicker;
exports.default = _default;