function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(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 _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_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 _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
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 _object_spread_props(target, source) {
    source = source != null ? source : {};
    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 _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { forwardRef, useState, useMemo } from "react";
import Tree from "rc-tree";
import cls from "classnames";
import { IconArrowWrapper, StyledArrow, base, StyledFolder, TitleWrapper, Title, ContentRight, Line, SpinnerStyled } from "./Tree.styles";
import { sizeToIconSize, traverseTree } from "./utils";
import { classes } from "./Tree.tokens";
/**
 * Многоуровневый раскрывающийся список в виде дерева.
 */ export var treeRoot = function treeRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(param, ref) {
        var items = param.items, _param_arrowPlacement = param.arrowPlacement, arrowPlacement = _param_arrowPlacement === void 0 ? 'left' : _param_arrowPlacement, _param_virtual = param.virtual, virtual = _param_virtual === void 0 ? true : _param_virtual, height = param.height, itemHeight = param.itemHeight, size = param.size, view = param.view, variant = param.variant, _param_fullWidthItemSelection = param.fullWidthItemSelection, fullWidthItemSelection = _param_fullWidthItemSelection === void 0 ? false : _param_fullWidthItemSelection, _param_multiple = param.multiple, multiple = _param_multiple === void 0 ? false : _param_multiple, _param_defaultExpandAll = param.defaultExpandAll, defaultExpandAll = _param_defaultExpandAll === void 0 ? false : _param_defaultExpandAll, _param_autoExpandParent = param.autoExpandParent, autoExpandParent = _param_autoExpandParent === void 0 ? false : _param_autoExpandParent, _param_checkable = param.checkable, checkable = _param_checkable === void 0 ? false : _param_checkable, outerSelectedKeys = param.selectedKeys, checkedKeys = param.checkedKeys, expandedKeys = param.expandedKeys, defaultCheckedKeys = param.defaultCheckedKeys, defaultExpandedKeys = param.defaultExpandedKeys, defaultSelectedKeys = param.defaultSelectedKeys, className = param.className, onTreeSelect = param.onTreeSelect, onTreeCheck = param.onTreeCheck, onTreeExpand = param.onTreeExpand, _param_hasIcon = param.hasIcon, hasIcon = _param_hasIcon === void 0 ? false : _param_hasIcon, icon = param.icon, renderTitle = param.renderTitle, _param_singleLine = param.singleLine, singleLine = _param_singleLine === void 0 ? true : _param_singleLine, _param_mode = param.mode, mode = _param_mode === void 0 ? 'default' : _param_mode, _param_draggable = param.draggable, draggable = _param_draggable === void 0 ? false : _param_draggable, onDragStart = param.onDragStart, onDragEnter = param.onDragEnter, onDragOver = param.onDragOver, onDragLeave = param.onDragLeave, onDragEnd = param.onDragEnd, onDrop = param.onDrop, allowDrop = param.allowDrop, loadData = param.loadData, onLoadData = param.onLoadData;
        var _useState = _sliced_to_array(useState(defaultSelectedKeys || []), 2), selected = _useState[0], setSelected = _useState[1];
        var selectedKeys = outerSelectedKeys !== null && outerSelectedKeys !== void 0 ? outerSelectedKeys : selected;
        var isRadioMode = mode === 'radio' && !multiple;
        var handleSelect = function handleSelect(updatedSelectedKeys, info) {
            if (!multiple && isRadioMode && updatedSelectedKeys.length === 0) {
                return;
            }
            setSelected(updatedSelectedKeys);
            if (onTreeSelect) {
                onTreeSelect(updatedSelectedKeys, info);
            }
        };
        var invertedClass = arrowPlacement === 'right' ? classes.treeInverted : undefined;
        var itemFilledClass = fullWidthItemSelection ? classes.treeItemFilled : undefined;
        var radioModeClass = isRadioMode ? classes.treeRadioMode : undefined;
        var tightVariantClass = variant === 'tight' ? classes.treeTightVariant : undefined;
        // Проходимся по дереву и устанавливаем соответствующие классы для узлов дерева,
        // чтобы соблюсти иерархию вложенности в UI.
        var treeData = useMemo(function() {
            return traverseTree(items, selectedKeys);
        }, [
            items,
            selectedKeys
        ]);
        return /*#__PURE__*/ React.createElement(Root, {
            view: view,
            size: size,
            variant: variant,
            ref: ref,
            items: items
        }, /*#__PURE__*/ React.createElement(Tree, _object_spread_props(_object_spread({
            loadData: loadData,
            onLoad: onLoadData,
            height: height,
            itemHeight: itemHeight,
            virtual: virtual,
            multiple: multiple,
            checkable: checkable,
            className: cls(className, invertedClass, itemFilledClass, radioModeClass, tightVariantClass),
            defaultExpandAll: defaultExpandAll,
            autoExpandParent: autoExpandParent,
            style: {
                border: '1px solid #000'
            },
            treeData: treeData,
            selectedKeys: selectedKeys
        }, checkedKeys !== undefined ? {
            checkedKeys: checkedKeys
        } : {}, expandedKeys !== undefined ? {
            expandedKeys: expandedKeys
        } : {}), {
            defaultCheckedKeys: defaultCheckedKeys,
            defaultExpandedKeys: defaultExpandedKeys,
            onSelect: handleSelect,
            // Тайп кастинг для упрощения API
            onCheck: onTreeCheck,
            onExpand: onTreeExpand,
            switcherIcon: function switcherIcon(node) {
                if (node.isLeaf) {
                    return null;
                }
                if (node.loading) {
                    return /*#__PURE__*/ React.createElement(SpinnerStyled, null);
                }
                return /*#__PURE__*/ React.createElement(IconArrowWrapper, null, /*#__PURE__*/ React.createElement(StyledArrow, {
                    size: sizeToIconSize(size, variant),
                    color: "inherit",
                    className: "arrow"
                }));
            },
            icon: hasIcon && (icon || /*#__PURE__*/ React.createElement(StyledFolder, {
                size: sizeToIconSize(size, variant),
                color: "inherit"
            })),
            titleRender: function titleRender(item) {
                return /*#__PURE__*/ React.createElement(TitleWrapper, {
                    fullWidthItemSelection: fullWidthItemSelection,
                    arrowPlacement: arrowPlacement,
                    singleLine: singleLine
                }, /*#__PURE__*/ React.createElement(Title, {
                    singleLine: singleLine
                }, renderTitle ? renderTitle(item) : typeof item.title === 'function' ? item.title(item) : item.title), item.contentRight && /*#__PURE__*/ React.createElement(ContentRight, null, item.contentRight));
            },
            draggable: draggable,
            onDragStart: onDragStart,
            onDragEnter: onDragEnter,
            onDragOver: onDragOver,
            onDragLeave: onDragLeave,
            onDragEnd: onDragEnd,
            onDrop: onDrop,
            allowDrop: allowDrop,
            dropIndicatorRender: function dropIndicatorRender(props) {
                var offset = 0;
                var dropPosition = props.dropPosition, dropLevelOffset = props.dropLevelOffset, indent = props.indent;
                var left = -dropLevelOffset * indent + offset;
                var style = {};
                if (dropPosition === 0) {
                    style.left = indent + offset;
                }
                return /*#__PURE__*/ React.createElement(Line, {
                    style: style,
                    left: left,
                    dropPosition: dropPosition,
                    variant: variant
                });
            }
        })));
    });
};
export var treeConfig = {
    name: 'Tree',
    tag: 'div',
    layout: treeRoot,
    base: base,
    variations: {},
    defaults: {
        view: 'default',
        size: 'm'
    }
};
