"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

var _vue = require("vue");

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

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

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

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

var _contextTypes = require("./contextTypes");

var _util = require("./util");

var _treeUtil = require("./utils/treeUtil");

var _NodeList = _interopRequireWildcard(require("./NodeList"));

var _conductUtil = require("./utils/conductUtil");

var _DropIndicator = _interopRequireDefault(require("./DropIndicator"));

var _initDefaultProps = _interopRequireDefault(require("../_util/props-util/initDefaultProps"));

var _props = require("./props");

var _warning = require("../vc-util/warning");

var _KeyCode = _interopRequireDefault(require("../_util/KeyCode"));

var _classNames2 = _interopRequireDefault(require("../_util/classNames"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }

var _default2 = (0, _vue.defineComponent)({
  name: 'Tree',
  inheritAttrs: false,
  slots: ['checkable', 'title', 'icon', 'titleRender'],
  props: (0, _initDefaultProps.default)((0, _props.treeProps)(), {
    prefixCls: 'vc-tree',
    showLine: false,
    showIcon: true,
    selectable: true,
    multiple: false,
    checkable: false,
    disabled: false,
    checkStrictly: false,
    draggable: false,
    defaultExpandParent: true,
    autoExpandParent: false,
    defaultExpandAll: false,
    defaultExpandedKeys: [],
    defaultCheckedKeys: [],
    defaultSelectedKeys: [],
    dropIndicatorRender: _DropIndicator.default,
    allowDrop: function allowDrop() {
      return true;
    }
  }),
  setup: function setup(props, _ref) {
    var attrs = _ref.attrs,
        slots = _ref.slots,
        expose = _ref.expose;
    var destroyed = (0, _vue.ref)(false);
    var delayedDragEnterLogic = {};
    var indent = (0, _vue.ref)();
    var selectedKeys = (0, _vue.shallowRef)([]);
    var checkedKeys = (0, _vue.shallowRef)([]);
    var halfCheckedKeys = (0, _vue.shallowRef)([]);
    var loadedKeys = (0, _vue.shallowRef)([]);
    var loadingKeys = (0, _vue.shallowRef)([]);
    var expandedKeys = (0, _vue.shallowRef)([]);
    var dragState = (0, _vue.reactive)({
      dragging: false,
      dragChildrenKeys: [],
      // dropTargetKey is the key of abstract-drop-node
      // the abstract-drop-node is the real drop node when drag and drop
      // not the DOM drag over node
      dropTargetKey: null,
      dropPosition: null,
      // the drop position of abstract-drop-node, inside 0, top -1, bottom 1
      dropContainerKey: null,
      // the container key of abstract-drop-node if dropPosition is -1 or 1
      dropLevelOffset: null,
      // the drop level offset of abstract-drag-over-node
      dropTargetPos: null,
      // the pos of abstract-drop-node
      dropAllowed: true,
      // if drop to abstract-drop-node is allowed
      // the abstract-drag-over-node
      // if mouse is on the bottom of top dom node or no the top of the bottom dom node
      // abstract-drag-over-node is the top node
      dragOverNodeKey: null
    });
    var treeData = (0, _vue.computed)(function () {
      return props.treeData !== undefined ? props.treeData : (0, _treeUtil.convertTreeToData)(props.children);
    });
    var keyEntities = (0, _vue.shallowRef)({});
    var focused = (0, _vue.ref)(false);
    var activeKey = (0, _vue.ref)(null);
    var listChanging = (0, _vue.ref)(false);
    var fieldNames = (0, _vue.computed)(function () {
      return (0, _treeUtil.fillFieldNames)(props.fieldNames);
    });
    var listRef = (0, _vue.ref)();
    var dragStartMousePosition = null;
    var dragNode = null;
    var treeNodeRequiredProps = (0, _vue.computed)(function () {
      return {
        expandedKeys: expandedKeys.value || [],
        selectedKeys: selectedKeys.value || [],
        loadedKeys: loadedKeys.value || [],
        loadingKeys: loadingKeys.value || [],
        checkedKeys: checkedKeys.value || [],
        halfCheckedKeys: halfCheckedKeys.value || [],
        dragOverNodeKey: dragState.dragOverNodeKey,
        dropPosition: dragState.dropPosition,
        keyEntities: keyEntities.value
      };
    });
    (0, _vue.watchEffect)(function () {
      if (treeData.value) {
        var entitiesMap = (0, _treeUtil.convertDataToEntities)(treeData.value, {
          fieldNames: fieldNames.value
        });
        keyEntities.value = (0, _objectSpread3.default)((0, _defineProperty2.default)({}, _NodeList.MOTION_KEY, _NodeList.MotionEntity), entitiesMap.keyEntities);
      }
    });
    var init = false; // 处理 defaultXxxx api, 仅仅首次有效

    (0, _vue.onMounted)(function () {
      init = true;
    }); // ================ expandedKeys =================

    (0, _vue.watchEffect)(function () {
      var keys = expandedKeys.value; // ================ expandedKeys =================

      if (props.expandedKeys !== undefined || init && props.autoExpandParent) {
        keys = props.autoExpandParent || !init && props.defaultExpandParent ? (0, _util.conductExpandParent)(props.expandedKeys, keyEntities.value) : props.expandedKeys;
      } else if (!init && props.defaultExpandAll) {
        var cloneKeyEntities = (0, _objectSpread3.default)({}, keyEntities.value);
        delete cloneKeyEntities[_NodeList.MOTION_KEY];
        keys = Object.keys(cloneKeyEntities).map(function (key) {
          return cloneKeyEntities[key].key;
        });
      } else if (!init && props.defaultExpandedKeys) {
        keys = props.autoExpandParent || props.defaultExpandParent ? (0, _util.conductExpandParent)(props.defaultExpandedKeys, keyEntities.value) : props.defaultExpandedKeys;
      }

      if (keys) {
        expandedKeys.value = keys;
      }
    }); // ================ flattenNodes =================

    var flattenNodes = (0, _vue.computed)(function () {
      return (0, _treeUtil.flattenTreeData)(treeData.value, expandedKeys.value, fieldNames.value);
    }); // ================ selectedKeys =================

    (0, _vue.watchEffect)(function () {
      if (props.selectable) {
        if (props.selectedKeys !== undefined) {
          selectedKeys.value = (0, _util.calcSelectedKeys)(props.selectedKeys, props);
        } else if (!init && props.defaultSelectedKeys) {
          selectedKeys.value = (0, _util.calcSelectedKeys)(props.defaultSelectedKeys, props);
        }
      }
    }); // ================= checkedKeys =================

    (0, _vue.watchEffect)(function () {
      if (props.checkable) {
        var checkedKeyEntity;

        if (props.checkedKeys !== undefined) {
          checkedKeyEntity = (0, _util.parseCheckedKeys)(props.checkedKeys) || {};
        } else if (!init && props.defaultCheckedKeys) {
          checkedKeyEntity = (0, _util.parseCheckedKeys)(props.defaultCheckedKeys) || {};
        } else if (treeData.value) {
          // If `treeData` changed, we also need check it
          checkedKeyEntity = (0, _util.parseCheckedKeys)(props.checkedKeys) || {
            checkedKeys: checkedKeys.value,
            halfCheckedKeys: halfCheckedKeys.value
          };
        }

        if (checkedKeyEntity) {
          var _checkedKeyEntity = checkedKeyEntity,
              _checkedKeyEntity$che = _checkedKeyEntity.checkedKeys,
              newCheckedKeys = _checkedKeyEntity$che === void 0 ? [] : _checkedKeyEntity$che,
              _checkedKeyEntity$hal = _checkedKeyEntity.halfCheckedKeys,
              newHalfCheckedKeys = _checkedKeyEntity$hal === void 0 ? [] : _checkedKeyEntity$hal;

          if (!props.checkStrictly) {
            var conductKeys = (0, _conductUtil.conductCheck)(newCheckedKeys, true, keyEntities.value);
            newCheckedKeys = conductKeys.checkedKeys;
            newHalfCheckedKeys = conductKeys.halfCheckedKeys;
          }

          checkedKeys.value = newCheckedKeys;
          halfCheckedKeys.value = newHalfCheckedKeys;
        }
      }
    }); // ================= loadedKeys ==================

    (0, _vue.watchEffect)(function () {
      if (props.loadedKeys) {
        loadedKeys.value = props.loadedKeys;
      }
    });

    var scrollTo = function scrollTo(scroll) {
      listRef.value.scrollTo(scroll);
    }; // =========================== Expanded ===========================

    /** Set uncontrolled `expandedKeys`. This will also auto update `flattenNodes`. */


    var setExpandedKeys = function setExpandedKeys(keys) {
      if (props.expandedKeys === undefined) {
        expandedKeys.value = keys;
      }
    };

    var cleanDragState = function cleanDragState() {
      if (dragState.dragging) {
        (0, _extends2.default)(dragState, {
          dragging: false,
          dropPosition: null,
          dropContainerKey: null,
          dropTargetKey: null,
          dropLevelOffset: null,
          dropAllowed: true,
          dragOverNodeKey: null
        });
      }

      dragStartMousePosition = null;
    }; // if onNodeDragEnd is called, onWindowDragEnd won't be called since stopPropagation() is called


    var onNodeDragEnd = function onNodeDragEnd(event, node) {
      var outsideTree = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var onDragend = props.onDragend;
      dragState.dragOverNodeKey = null;
      cleanDragState();

      if (onDragend && !outsideTree) {
        onDragend({
          event: event,
          node: node.eventData
        });
      }

      dragNode = null;
    }; // since stopPropagation() is called in treeNode
    // if onWindowDrag is called, whice means state is keeped, drag state should be cleared


    var onWindowDragEnd = function onWindowDragEnd(event) {
      onNodeDragEnd(event, null, true);
      window.removeEventListener('dragend', onWindowDragEnd);
    };

    var onNodeDragStart = function onNodeDragStart(event, node) {
      var onDragstart = props.onDragstart;
      var eventKey = node.eventKey,
          eventData = node.eventData;
      dragNode = node;
      dragStartMousePosition = {
        x: event.clientX,
        y: event.clientY
      };
      var newExpandedKeys = (0, _util.arrDel)(expandedKeys.value, eventKey);
      dragState.dragging = true;
      dragState.dragChildrenKeys = (0, _util.getDragChildrenKeys)(eventKey, keyEntities.value);
      indent.value = listRef.value.getIndentWidth();
      setExpandedKeys(newExpandedKeys);
      window.addEventListener('dragend', onWindowDragEnd);

      if (onDragstart) {
        onDragstart({
          event: event,
          node: eventData
        });
      }
    };
    /**
     * [Legacy] Select handler is smaller than node,
     * so that this will trigger when drag enter node or select handler.
     * This is a little tricky if customize css without padding.
     * Better for use mouse move event to refresh drag state.
     * But let's just keep it to avoid event trigger logic change.
     */


    var onNodeDragEnter = function onNodeDragEnter(event, node) {
      var onDragenter = props.onDragenter,
          onExpand = props.onExpand,
          allowDrop = props.allowDrop,
          direction = props.direction;

      var _calcDropPosition = (0, _util.calcDropPosition)(event, dragNode, node, indent.value, dragStartMousePosition, allowDrop, flattenNodes.value, keyEntities.value, expandedKeys.value, direction),
          dropPosition = _calcDropPosition.dropPosition,
          dropLevelOffset = _calcDropPosition.dropLevelOffset,
          dropTargetKey = _calcDropPosition.dropTargetKey,
          dropContainerKey = _calcDropPosition.dropContainerKey,
          dropTargetPos = _calcDropPosition.dropTargetPos,
          dropAllowed = _calcDropPosition.dropAllowed,
          dragOverNodeKey = _calcDropPosition.dragOverNodeKey;

      if (!dragNode || // don't allow drop inside its children
      dragState.dragChildrenKeys.indexOf(dropTargetKey) !== -1 || // don't allow drop when drop is not allowed caculated by calcDropPosition
      !dropAllowed) {
        (0, _extends2.default)(dragState, {
          dragOverNodeKey: null,
          dropPosition: null,
          dropLevelOffset: null,
          dropTargetKey: null,
          dropContainerKey: null,
          dropTargetPos: null,
          dropAllowed: false
        });
        return;
      } // Side effect for delay drag


      if (!delayedDragEnterLogic) {
        delayedDragEnterLogic = {};
      }

      Object.keys(delayedDragEnterLogic).forEach(function (key) {
        clearTimeout(delayedDragEnterLogic[key]);
      });

      if (dragNode.eventKey !== node.eventKey) {
        // hoist expand logic here
        // since if logic is on the bottom
        // it will be blocked by abstract dragover node check
        //   => if you dragenter from top, you mouse will still be consider as in the top node
        delayedDragEnterLogic[node.pos] = window.setTimeout(function () {
          if (!dragState.dragging) return;
          var newExpandedKeys = (0, _toConsumableArray2.default)(expandedKeys.value);
          var entity = keyEntities.value[node.eventKey];

          if (entity && (entity.children || []).length) {
            newExpandedKeys = (0, _util.arrAdd)(expandedKeys.value, node.eventKey);
          }

          setExpandedKeys(newExpandedKeys);

          if (onExpand) {
            onExpand(newExpandedKeys, {
              node: node.eventData,
              expanded: true,
              nativeEvent: event
            });
          }
        }, 800);
      } // Skip if drag node is self


      if (dragNode.eventKey === dropTargetKey && dropLevelOffset === 0) {
        (0, _extends2.default)(dragState, {
          dragOverNodeKey: null,
          dropPosition: null,
          dropLevelOffset: null,
          dropTargetKey: null,
          dropContainerKey: null,
          dropTargetPos: null,
          dropAllowed: false
        });
        return;
      } // Update drag over node and drag state


      (0, _extends2.default)(dragState, {
        dragOverNodeKey: dragOverNodeKey,
        dropPosition: dropPosition,
        dropLevelOffset: dropLevelOffset,
        dropTargetKey: dropTargetKey,
        dropContainerKey: dropContainerKey,
        dropTargetPos: dropTargetPos,
        dropAllowed: dropAllowed
      });

      if (onDragenter) {
        onDragenter({
          event: event,
          node: node.eventData,
          expandedKeys: expandedKeys.value
        });
      }
    };

    var onNodeDragOver = function onNodeDragOver(event, node) {
      var onDragover = props.onDragover,
          allowDrop = props.allowDrop,
          direction = props.direction;

      var _calcDropPosition2 = (0, _util.calcDropPosition)(event, dragNode, node, indent.value, dragStartMousePosition, allowDrop, flattenNodes.value, keyEntities.value, expandedKeys.value, direction),
          dropPosition = _calcDropPosition2.dropPosition,
          dropLevelOffset = _calcDropPosition2.dropLevelOffset,
          dropTargetKey = _calcDropPosition2.dropTargetKey,
          dropContainerKey = _calcDropPosition2.dropContainerKey,
          dropAllowed = _calcDropPosition2.dropAllowed,
          dropTargetPos = _calcDropPosition2.dropTargetPos,
          dragOverNodeKey = _calcDropPosition2.dragOverNodeKey;

      if (!dragNode || dragState.dragChildrenKeys.indexOf(dropTargetKey) !== -1 || !dropAllowed) {
        // don't allow drop inside its children
        // don't allow drop when drop is not allowed caculated by calcDropPosition
        return;
      } // Update drag position


      if (dragNode.eventKey === dropTargetKey && dropLevelOffset === 0) {
        if (!(dragState.dropPosition === null && dragState.dropLevelOffset === null && dragState.dropTargetKey === null && dragState.dropContainerKey === null && dragState.dropTargetPos === null && dragState.dropAllowed === false && dragState.dragOverNodeKey === null)) {
          (0, _extends2.default)(dragState, {
            dropPosition: null,
            dropLevelOffset: null,
            dropTargetKey: null,
            dropContainerKey: null,
            dropTargetPos: null,
            dropAllowed: false,
            dragOverNodeKey: null
          });
        }
      } else if (!(dropPosition === dragState.dropPosition && dropLevelOffset === dragState.dropLevelOffset && dropTargetKey === dragState.dropTargetKey && dropContainerKey === dragState.dropContainerKey && dropTargetPos === dragState.dropTargetPos && dropAllowed === dragState.dropAllowed && dragOverNodeKey === dragState.dragOverNodeKey)) {
        (0, _extends2.default)(dragState, {
          dropPosition: dropPosition,
          dropLevelOffset: dropLevelOffset,
          dropTargetKey: dropTargetKey,
          dropContainerKey: dropContainerKey,
          dropTargetPos: dropTargetPos,
          dropAllowed: dropAllowed,
          dragOverNodeKey: dragOverNodeKey
        });
      }

      if (onDragover) {
        onDragover({
          event: event,
          node: node.eventData
        });
      }
    };

    var onNodeDragLeave = function onNodeDragLeave(event, node) {
      var onDragleave = props.onDragleave;

      if (onDragleave) {
        onDragleave({
          event: event,
          node: node.eventData
        });
      }
    };

    var onNodeDrop = function onNodeDrop(event, _node) {
      var _activeItem$value;

      var outsideTree = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var dragChildrenKeys = dragState.dragChildrenKeys,
          dropPosition = dragState.dropPosition,
          dropTargetKey = dragState.dropTargetKey,
          dropTargetPos = dragState.dropTargetPos,
          dropAllowed = dragState.dropAllowed;
      if (!dropAllowed) return;
      var onDrop = props.onDrop;
      dragState.dragOverNodeKey = null;
      cleanDragState();
      if (dropTargetKey === null) return;
      var abstractDropNodeProps = (0, _objectSpread3.default)((0, _objectSpread3.default)({}, (0, _treeUtil.getTreeNodeProps)(dropTargetKey, treeNodeRequiredProps.value)), {}, {
        active: ((_activeItem$value = activeItem.value) === null || _activeItem$value === void 0 ? void 0 : _activeItem$value.key) === dropTargetKey,
        data: keyEntities.value[dropTargetKey].node
      });
      var dropToChild = dragChildrenKeys.indexOf(dropTargetKey) !== -1;
      (0, _warning.warning)(!dropToChild, "Can not drop to dragNode's children node. Maybe this is a bug of ant-design-vue. Please report an issue.");
      var posArr = (0, _util.posToArr)(dropTargetPos);
      var dropResult = {
        event: event,
        node: (0, _treeUtil.convertNodePropsToEventData)(abstractDropNodeProps),
        dragNode: dragNode ? dragNode.eventData : null,
        dragNodesKeys: [dragNode.eventKey].concat(dragChildrenKeys),
        dropToGap: dropPosition !== 0,
        dropPosition: dropPosition + Number(posArr[posArr.length - 1])
      };

      if (onDrop && !outsideTree) {
        onDrop(dropResult);
      }

      dragNode = null;
    };

    var onNodeClick = function onNodeClick(e, treeNode) {
      var onClick = props.onClick;

      if (onClick) {
        onClick(e, treeNode);
      }
    };

    var onNodeDoubleClick = function onNodeDoubleClick(e, treeNode) {
      var onDblclick = props.onDblclick;

      if (onDblclick) {
        onDblclick(e, treeNode);
      }
    };

    var onNodeSelect = function onNodeSelect(e, treeNode) {
      var newSelectedKeys = selectedKeys.value;
      var onSelect = props.onSelect,
          multiple = props.multiple;
      var selected = treeNode.selected;
      var key = treeNode[fieldNames.value.key];
      var targetSelected = !selected; // Update selected keys

      if (!targetSelected) {
        newSelectedKeys = (0, _util.arrDel)(newSelectedKeys, key);
      } else if (!multiple) {
        newSelectedKeys = [key];
      } else {
        newSelectedKeys = (0, _util.arrAdd)(newSelectedKeys, key);
      } // [Legacy] Not found related usage in doc or upper libs


      var keyEntitiesValue = keyEntities.value;
      var selectedNodes = newSelectedKeys.map(function (selectedKey) {
        var entity = keyEntitiesValue[selectedKey];
        if (!entity) return null;
        return entity.node;
      }).filter(function (node) {
        return node;
      });

      if (props.selectedKeys === undefined) {
        selectedKeys.value = newSelectedKeys;
      }

      if (onSelect) {
        onSelect(newSelectedKeys, {
          event: 'select',
          selected: targetSelected,
          node: treeNode,
          selectedNodes: selectedNodes,
          nativeEvent: e
        });
      }
    };

    var onNodeCheck = function onNodeCheck(e, treeNode, checked) {
      var checkStrictly = props.checkStrictly,
          onCheck = props.onCheck;
      var key = treeNode[fieldNames.value.key]; // Prepare trigger arguments

      var checkedObj;
      var eventObj = {
        event: 'check',
        node: treeNode,
        checked: checked,
        nativeEvent: e
      };

      if (checkStrictly) {
        var newCheckedKeys = checked ? (0, _util.arrAdd)(checkedKeys.value, key) : (0, _util.arrDel)(checkedKeys.value, key);
        var newHalfCheckedKeys = (0, _util.arrDel)(halfCheckedKeys.value, key);
        checkedObj = {
          checked: newCheckedKeys,
          halfChecked: newHalfCheckedKeys
        };
        var keyEntitiesValue = keyEntities.value;
        eventObj.checkedNodes = newCheckedKeys.map(function (checkedKey) {
          return keyEntitiesValue[checkedKey];
        }).filter(function (entity) {
          return entity;
        }).map(function (entity) {
          return entity.node;
        });

        if (props.checkedKeys === undefined) {
          checkedKeys.value = newCheckedKeys;
        }
      } else {
        // Always fill first
        var _conductCheck = (0, _conductUtil.conductCheck)([].concat((0, _toConsumableArray2.default)(checkedKeys.value), [key]), true, keyEntities.value),
            _newCheckedKeys = _conductCheck.checkedKeys,
            _newHalfCheckedKeys = _conductCheck.halfCheckedKeys; // If remove, we do it again to correction


        if (!checked) {
          var keySet = new Set(_newCheckedKeys);
          keySet.delete(key);

          var _conductCheck2 = (0, _conductUtil.conductCheck)(Array.from(keySet), {
            checked: false,
            halfCheckedKeys: _newHalfCheckedKeys
          }, keyEntities.value);

          _newCheckedKeys = _conductCheck2.checkedKeys;
          _newHalfCheckedKeys = _conductCheck2.halfCheckedKeys;
        }

        checkedObj = _newCheckedKeys; // [Legacy] This is used for vc-tree-select`

        eventObj.checkedNodes = [];
        eventObj.checkedNodesPositions = [];
        eventObj.halfCheckedKeys = _newHalfCheckedKeys;

        _newCheckedKeys.forEach(function (checkedKey) {
          var entity = keyEntities.value[checkedKey];
          if (!entity) return;
          var node = entity.node,
              pos = entity.pos;
          eventObj.checkedNodes.push(node);
          eventObj.checkedNodesPositions.push({
            node: node,
            pos: pos
          });
        });

        if (props.checkedKeys === undefined) {
          checkedKeys.value = _newCheckedKeys;
          halfCheckedKeys.value = _newHalfCheckedKeys;
        }
      }

      if (onCheck) {
        onCheck(checkedObj, eventObj);
      }
    };

    var onNodeLoad = function onNodeLoad(treeNode) {
      return new Promise(function (resolve, reject) {
        // We need to get the latest state of loading/loaded keys
        var loadData = props.loadData,
            onLoad = props.onLoad;
        var key = treeNode[fieldNames.value.key];

        if (!loadData || loadedKeys.value.indexOf(key) !== -1 || loadingKeys.value.indexOf(key) !== -1) {
          return null;
        } // Process load data


        var promise = loadData(treeNode);
        promise.then(function () {
          var newLoadedKeys = (0, _util.arrAdd)(loadedKeys.value, key);
          var newLoadingKeys = (0, _util.arrDel)(loadingKeys.value, key); // onLoad should trigger before internal setState to avoid `loadData` trigger twice.
          // https://github.com/ant-design/ant-design/issues/12464

          if (onLoad) {
            onLoad(newLoadedKeys, {
              event: 'load',
              node: treeNode
            });
          }

          if (props.loadedKeys === undefined) {
            loadedKeys.value = newLoadedKeys;
          }

          loadingKeys.value = newLoadingKeys;
          resolve();
        }).catch(function (e) {
          var newLoadingKeys = (0, _util.arrDel)(loadingKeys.value, key);
          loadingKeys.value = newLoadingKeys;
          reject(e);
        });
        loadingKeys.value = (0, _util.arrAdd)(loadingKeys.value, key);
      });
    };

    var onNodeMouseEnter = function onNodeMouseEnter(event, node) {
      var onMouseenter = props.onMouseenter;

      if (onMouseenter) {
        onMouseenter({
          event: event,
          node: node
        });
      }
    };

    var onNodeMouseLeave = function onNodeMouseLeave(event, node) {
      var onMouseleave = props.onMouseleave;

      if (onMouseleave) {
        onMouseleave({
          event: event,
          node: node
        });
      }
    };

    var onNodeContextMenu = function onNodeContextMenu(event, node) {
      var onRightClick = props.onRightClick;

      if (onRightClick) {
        event.preventDefault();
        onRightClick({
          event: event,
          node: node
        });
      }
    };

    var onFocus = function onFocus(e) {
      var onFocus = props.onFocus;
      focused.value = true;

      if (onFocus) {
        onFocus(e);
      }
    };

    var onBlur = function onBlur(e) {
      var onBlur = props.onBlur;
      focused.value = false;
      onActiveChange(null);

      if (onBlur) {
        onBlur(e);
      }
    };

    var onNodeExpand = function onNodeExpand(e, treeNode) {
      var newExpandedKeys = expandedKeys.value;
      var onExpand = props.onExpand,
          loadData = props.loadData;
      var expanded = treeNode.expanded;
      var key = treeNode[fieldNames.value.key]; // Do nothing when motion is in progress

      if (listChanging.value) {
        return;
      } // Update selected keys


      var index = newExpandedKeys.indexOf(key);
      var targetExpanded = !expanded;
      (0, _warning.warning)(expanded && index !== -1 || !expanded && index === -1, 'Expand state not sync with index check');

      if (targetExpanded) {
        newExpandedKeys = (0, _util.arrAdd)(newExpandedKeys, key);
      } else {
        newExpandedKeys = (0, _util.arrDel)(newExpandedKeys, key);
      }

      setExpandedKeys(newExpandedKeys);

      if (onExpand) {
        onExpand(newExpandedKeys, {
          node: treeNode,
          expanded: targetExpanded,
          nativeEvent: e
        });
      } // Async Load data


      if (targetExpanded && loadData) {
        var loadPromise = onNodeLoad(treeNode);

        if (loadPromise) {
          loadPromise.then(function () {// [Legacy] Refresh logic
            // const newFlattenTreeData = flattenTreeData(
            //   treeData.value,
            //   newExpandedKeys,
            //   fieldNames.value,
            // );
            // flattenNodes.value = newFlattenTreeData;
          }).catch(function (e) {
            var expandedKeysToRestore = (0, _util.arrDel)(expandedKeys.value, key);
            setExpandedKeys(expandedKeysToRestore);
            Promise.reject(e);
          });
        }
      }
    };

    var onListChangeStart = function onListChangeStart() {
      listChanging.value = true;
    };

    var onListChangeEnd = function onListChangeEnd() {
      setTimeout(function () {
        listChanging.value = false;
      });
    }; // =========================== Keyboard ===========================


    var onActiveChange = function onActiveChange(newActiveKey) {
      var onActiveChange = props.onActiveChange;

      if (activeKey.value === newActiveKey) {
        return;
      }

      activeKey.value = newActiveKey;

      if (newActiveKey !== null) {
        scrollTo({
          key: newActiveKey
        });
      }

      if (onActiveChange) {
        onActiveChange(newActiveKey);
      }
    };

    var activeItem = (0, _vue.computed)(function () {
      if (activeKey.value === null) {
        return null;
      }

      return flattenNodes.value.find(function (_ref2) {
        var key = _ref2.key;
        return key === activeKey.value;
      }) || null;
    });

    var offsetActiveKey = function offsetActiveKey(offset) {
      var index = flattenNodes.value.findIndex(function (_ref3) {
        var key = _ref3.key;
        return key === activeKey.value;
      }); // Align with index

      if (index === -1 && offset < 0) {
        index = flattenNodes.value.length;
      }

      index = (index + offset + flattenNodes.value.length) % flattenNodes.value.length;
      var item = flattenNodes.value[index];

      if (item) {
        var key = item.key;
        onActiveChange(key);
      } else {
        onActiveChange(null);
      }
    };

    var activeItemEventNode = (0, _vue.computed)(function () {
      return (0, _treeUtil.convertNodePropsToEventData)((0, _objectSpread3.default)((0, _objectSpread3.default)({}, (0, _treeUtil.getTreeNodeProps)(activeKey.value, treeNodeRequiredProps.value)), {}, {
        data: activeItem.value.data,
        active: true
      }));
    });

    var onKeydown = function onKeydown(event) {
      var onKeydown = props.onKeydown,
          checkable = props.checkable,
          selectable = props.selectable; // >>>>>>>>>> Direction

      switch (event.which) {
        case _KeyCode.default.UP:
          {
            offsetActiveKey(-1);
            event.preventDefault();
            break;
          }

        case _KeyCode.default.DOWN:
          {
            offsetActiveKey(1);
            event.preventDefault();
            break;
          }
      } // >>>>>>>>>> Expand & Selection


      var item = activeItem.value;

      if (item && item.data) {
        var expandable = item.data.isLeaf === false || !!(item.data.children || []).length;
        var eventNode = activeItemEventNode.value;

        switch (event.which) {
          // >>> Expand
          case _KeyCode.default.LEFT:
            {
              // Collapse if possible
              if (expandable && expandedKeys.value.includes(activeKey.value)) {
                onNodeExpand({}, eventNode);
              } else if (item.parent) {
                onActiveChange(item.parent.key);
              }

              event.preventDefault();
              break;
            }

          case _KeyCode.default.RIGHT:
            {
              // Expand if possible
              if (expandable && !expandedKeys.value.includes(activeKey.value)) {
                onNodeExpand({}, eventNode);
              } else if (item.children && item.children.length) {
                onActiveChange(item.children[0].key);
              }

              event.preventDefault();
              break;
            }
          // Selection

          case _KeyCode.default.ENTER:
          case _KeyCode.default.SPACE:
            {
              if (checkable && !eventNode.disabled && eventNode.checkable !== false && !eventNode.disableCheckbox) {
                onNodeCheck({}, eventNode, !checkedKeys.value.includes(activeKey.value));
              } else if (!checkable && selectable && !eventNode.disabled && eventNode.selectable !== false) {
                onNodeSelect({}, eventNode);
              }

              break;
            }
        }
      }

      if (onKeydown) {
        onKeydown(event);
      }
    };

    expose({
      onNodeExpand: onNodeExpand,
      scrollTo: scrollTo,
      onKeydown: onKeydown,
      selectedKeys: (0, _vue.computed)(function () {
        return selectedKeys.value;
      }),
      checkedKeys: (0, _vue.computed)(function () {
        return checkedKeys.value;
      }),
      halfCheckedKeys: (0, _vue.computed)(function () {
        return halfCheckedKeys.value;
      }),
      loadedKeys: (0, _vue.computed)(function () {
        return loadedKeys.value;
      }),
      loadingKeys: (0, _vue.computed)(function () {
        return loadingKeys.value;
      }),
      expandedKeys: (0, _vue.computed)(function () {
        return expandedKeys.value;
      })
    });
    (0, _vue.onUnmounted)(function () {
      window.removeEventListener('dragend', onWindowDragEnd);
      destroyed.value = true;
    });
    return function () {
      var _classNames;

      var dragging = dragState.dragging,
          dropLevelOffset = dragState.dropLevelOffset,
          dropContainerKey = dragState.dropContainerKey,
          dropTargetKey = dragState.dropTargetKey,
          dropPosition = dragState.dropPosition,
          dragOverNodeKey = dragState.dragOverNodeKey;
      var prefixCls = props.prefixCls,
          showLine = props.showLine,
          focusable = props.focusable,
          _props$tabindex = props.tabindex,
          tabindex = _props$tabindex === void 0 ? 0 : _props$tabindex,
          selectable = props.selectable,
          showIcon = props.showIcon,
          _props$icon = props.icon,
          icon = _props$icon === void 0 ? slots.icon : _props$icon,
          switcherIcon = props.switcherIcon,
          draggable = props.draggable,
          checkable = props.checkable,
          checkStrictly = props.checkStrictly,
          disabled = props.disabled,
          motion = props.motion,
          loadData = props.loadData,
          filterTreeNode = props.filterTreeNode,
          height = props.height,
          itemHeight = props.itemHeight,
          virtual = props.virtual,
          dropIndicatorRender = props.dropIndicatorRender,
          onContextmenu = props.onContextmenu,
          onScroll = props.onScroll,
          direction = props.direction;
      var className = attrs.class,
          style = attrs.style;
      var domProps = (0, _util.getDataAndAria)((0, _objectSpread3.default)((0, _objectSpread3.default)({}, props), attrs));
      return (0, _vue.createVNode)(_contextTypes.TreeContext, {
        "value": {
          prefixCls: prefixCls,
          selectable: selectable,
          showIcon: showIcon,
          icon: icon,
          switcherIcon: switcherIcon,
          draggable: draggable,
          checkable: checkable,
          customCheckable: slots.checkable,
          checkStrictly: checkStrictly,
          disabled: disabled,
          keyEntities: keyEntities.value,
          dropLevelOffset: dropLevelOffset,
          dropContainerKey: dropContainerKey,
          dropTargetKey: dropTargetKey,
          dropPosition: dropPosition,
          dragOverNodeKey: dragOverNodeKey,
          indent: indent.value,
          direction: direction,
          dropIndicatorRender: dropIndicatorRender,
          loadData: loadData,
          filterTreeNode: filterTreeNode,
          onNodeClick: onNodeClick,
          onNodeDoubleClick: onNodeDoubleClick,
          onNodeExpand: onNodeExpand,
          onNodeSelect: onNodeSelect,
          onNodeCheck: onNodeCheck,
          onNodeLoad: onNodeLoad,
          onNodeMouseEnter: onNodeMouseEnter,
          onNodeMouseLeave: onNodeMouseLeave,
          onNodeContextMenu: onNodeContextMenu,
          onNodeDragStart: onNodeDragStart,
          onNodeDragEnter: onNodeDragEnter,
          onNodeDragOver: onNodeDragOver,
          onNodeDragLeave: onNodeDragLeave,
          onNodeDragEnd: onNodeDragEnd,
          onNodeDrop: onNodeDrop,
          slots: slots
        }
      }, {
        default: function _default() {
          return [(0, _vue.createVNode)("div", {
            "role": "tree",
            "class": (0, _classNames2.default)(prefixCls, className, (_classNames = {}, (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-show-line"), showLine), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-focused"), focused.value), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-active-focused"), activeKey.value !== null), _classNames))
          }, [(0, _vue.createVNode)(_NodeList.default, (0, _objectSpread3.default)((0, _objectSpread3.default)({
            "ref": listRef,
            "prefixCls": prefixCls,
            "style": style,
            "data": flattenNodes.value,
            "disabled": disabled,
            "selectable": selectable,
            "checkable": !!checkable,
            "motion": motion,
            "dragging": dragging,
            "height": height,
            "itemHeight": itemHeight,
            "virtual": virtual,
            "focusable": focusable,
            "focused": focused.value,
            "tabindex": tabindex,
            "activeItem": activeItem.value,
            "onFocus": onFocus,
            "onBlur": onBlur,
            "onKeydown": onKeydown,
            "onActiveChange": onActiveChange,
            "onListChangeStart": onListChangeStart,
            "onListChangeEnd": onListChangeEnd,
            "onContextmenu": onContextmenu,
            "onScroll": onScroll
          }, treeNodeRequiredProps.value), domProps), null)])];
        }
      });
    };
  }
});

exports.default = _default2;