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 { FileFolders } from "@sofa-design/icons";
import { ConfigProvider, Empty, Tree, Typography } from "antd";
import classNames from "clsx";
import React, { useContext, useEffect, useMemo, useState } from "react";
import { useRefFunction } from "../../../Hooks/useRefFunction";
import { I18nContext, compileTemplate } from "../../../I18n";
import { getFileType } from "../../types";
import { FileItem } from "../components/FileItem";
import { resolveTreeLeafFile } from "../resolveTreeLeafFile";
import { useFileStyle } from "../style";
import { getFileTypeIcon } from "../utils";
import { useFileTreeStyle } from "./style";
var walkAndIndex = function walkAndIndex1(nodes, map) {
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var n = _step.value;
            var _n_children;
            map.set(n.key, n);
            if ((_n_children = n.children) === null || _n_children === void 0 ? void 0 : _n_children.length) {
                walkAndIndex(n.children, map);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
};
var mapTreeToDataNodes = function mapTreeToDataNodes1(nodes, ctx) {
    return nodes.map(function(node) {
        var _node_isLeaf;
        var hasChildren = Boolean(node.children && node.children.length > 0);
        var resolvedIsLeaf = (_node_isLeaf = node.isLeaf) !== null && _node_isLeaf !== void 0 ? _node_isLeaf : !hasChildren;
        if (resolvedIsLeaf) {
            var leafFile = resolveTreeLeafFile(node, ctx.resolveTreeLeafFileOptions);
            var title = leafFile !== null ? /*#__PURE__*/ React.createElement(FileItem, {
                layout: "tree",
                file: node.disabled === true ? _object_spread_props(_object_spread({}, leafFile), {
                    disabled: true
                }) : leafFile,
                prefixCls: ctx.fileItemPrefixCls,
                hashId: ctx.fileItemHashId,
                locale: ctx.locale,
                onDownload: ctx.onDownload,
                onPreview: ctx.onPreview,
                onShare: ctx.onShare,
                onLocate: ctx.onLocate
            }) : node.name;
            return {
                key: node.key,
                title: title,
                isLeaf: true,
                disabled: node.disabled
            };
        }
        return {
            key: node.key,
            title: node.name,
            isLeaf: false,
            disabled: node.disabled,
            children: hasChildren ? mapTreeToDataNodes(node.children, ctx) : []
        };
    });
};
var replaceNodeChildren = function replaceNodeChildren1(nodes, key, newChildren) {
    return nodes.map(function(n) {
        var _n_children;
        if (n.key === key) {
            return _object_spread_props(_object_spread({}, n), {
                children: newChildren
            });
        }
        if ((_n_children = n.children) === null || _n_children === void 0 ? void 0 : _n_children.length) {
            return _object_spread_props(_object_spread({}, n), {
                children: replaceNodeChildren(n.children, key, newChildren)
            });
        }
        return n;
    });
};
var buildMap = function buildMap(nodes) {
    var m = new Map();
    walkAndIndex(nodes, m);
    return m;
};
/**
 * 仅对已展开目录下的已加载子树做名称匹配；未展开目录内的节点不参与匹配
 */ var filterFileTreeByExpandedKeyword = function filterFileTreeByExpandedKeyword(nodes, expandedSet, rawKeyword) {
    var q = rawKeyword.trim().toLowerCase();
    if (!q) return nodes;
    var visit = function visit1(node) {
        var _node_isLeaf, _node_children;
        var selfMatch = node.name.toLowerCase().includes(q);
        var hasChildren = Boolean(node.children && node.children.length > 0);
        var resolvedIsLeaf = (_node_isLeaf = node.isLeaf) !== null && _node_isLeaf !== void 0 ? _node_isLeaf : !hasChildren;
        if (resolvedIsLeaf) {
            return selfMatch ? node : null;
        }
        if (!expandedSet.has(node.key)) {
            var _node_children1;
            return _object_spread_props(_object_spread({}, node), {
                children: (_node_children1 = node.children) !== null && _node_children1 !== void 0 ? _node_children1 : []
            });
        }
        var rawChildren = (_node_children = node.children) !== null && _node_children !== void 0 ? _node_children : [];
        if (rawChildren.length === 0 && node.isLeaf === false) {
            return _object_spread_props(_object_spread({}, node), {
                children: []
            });
        }
        var filteredChildren = rawChildren.map(visit).filter(function(n) {
            return Boolean(n);
        });
        if (selfMatch || filteredChildren.length > 0) {
            return _object_spread_props(_object_spread({}, node), {
                children: filteredChildren
            });
        }
        return null;
    };
    return nodes.map(visit).filter(function(n) {
        return Boolean(n);
    });
};
var collectSubtreeKeys = function collectSubtreeKeys(nodes) {
    var keys = new Set();
    var walk = function walk1(ns) {
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            for(var _iterator = ns[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var n = _step.value;
                var _n_children;
                keys.add(n.key);
                if ((_n_children = n.children) === null || _n_children === void 0 ? void 0 : _n_children.length) walk(n.children);
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
    };
    walk(nodes);
    return keys;
};
var FileTreeComponent = function FileTreeComponent(param) {
    var _tab = param.tab, className = param.className, style = param.style, treeData = param.treeData, onLoadChildren = param.onLoadChildren, onSelect = param.onSelect, onFileClick = param.onFileClick, onDownload = param.onDownload, onPreview = param.onPreview, onShare = param.onShare, onLocate = param.onLocate, _param_showLine = param.showLine, showLine = _param_showLine === void 0 ? true : _param_showLine, _resetKey = param.resetKey, emptyRender = param.emptyRender, _param_blockNode = param.blockNode, blockNode = _param_blockNode === void 0 ? true : _param_blockNode, filterKeyword = param.filterKeyword, fileItemPrefixClsProp = param.fileItemPrefixCls, fileItemHashIdProp = param.fileItemHashId, fileNodeByRelativePath = param.fileNodeByRelativePath;
    var _ref, _ref1, _ref2;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var locale = useContext(I18nContext).locale;
    var prefixCls = getPrefixCls('workspace-file-tree');
    var fileItemPrefixCls = fileItemPrefixClsProp !== null && fileItemPrefixClsProp !== void 0 ? fileItemPrefixClsProp : getPrefixCls('workspace-file');
    var _useFileTreeStyle = useFileTreeStyle(prefixCls), wrapSSR = _useFileTreeStyle.wrapSSR, hashId = _useFileTreeStyle.hashId;
    var _useFileStyle = useFileStyle(fileItemPrefixCls), wrapFileItemSSR = _useFileStyle.wrapSSR, fileItemStyleHashId = _useFileStyle.hashId;
    var fileItemHashId = fileItemHashIdProp !== null && fileItemHashIdProp !== void 0 ? fileItemHashIdProp : fileItemStyleHashId;
    var injectFileItemStyles = fileItemHashIdProp === undefined;
    var _useState = _sliced_to_array(useState(treeData), 2), innerTree = _useState[0], setInnerTree = _useState[1];
    var _useState1 = _sliced_to_array(useState([]), 2), expandedKeys = _useState1[0], setExpandedKeys = _useState1[1];
    var nodeMap = useMemo(function() {
        return buildMap(innerTree);
    }, [
        innerTree
    ]);
    var onLoadChildrenRef = useRefFunction(onLoadChildren);
    useEffect(function() {
        setInnerTree(treeData);
    }, [
        treeData
    ]);
    useEffect(function() {
        if (_resetKey === undefined) return;
        setExpandedKeys([]);
    }, [
        _resetKey
    ]);
    var expandedSet = useMemo(function() {
        return new Set(expandedKeys.map(function(k) {
            return String(k);
        }));
    }, [
        expandedKeys
    ]);
    var displayTree = useMemo(function() {
        if (!(filterKeyword === null || filterKeyword === void 0 ? void 0 : filterKeyword.trim())) return innerTree;
        return filterFileTreeByExpandedKeyword(innerTree, expandedSet, filterKeyword);
    }, [
        innerTree,
        expandedSet,
        filterKeyword
    ]);
    var keysInDisplayTree = useMemo(function() {
        return collectSubtreeKeys(displayTree);
    }, [
        displayTree
    ]);
    var safeExpandedKeys = useMemo(function() {
        return expandedKeys.filter(function(k) {
            return keysInDisplayTree.has(String(k));
        });
    }, [
        expandedKeys,
        keysInDisplayTree
    ]);
    var resolveTreeLeafFileOptions = useMemo(function() {
        return {
            fileNodeByRelativePath: fileNodeByRelativePath
        };
    }, [
        fileNodeByRelativePath
    ]);
    var dataNodes = useMemo(function() {
        return mapTreeToDataNodes(displayTree, {
            prefixCls: prefixCls,
            hashId: hashId,
            fileItemPrefixCls: fileItemPrefixCls,
            fileItemHashId: fileItemHashId,
            locale: locale,
            onDownload: onDownload,
            onPreview: onPreview,
            onShare: onShare,
            onLocate: onLocate,
            resolveTreeLeafFileOptions: resolveTreeLeafFileOptions
        });
    }, [
        displayTree,
        prefixCls,
        hashId,
        fileItemPrefixCls,
        fileItemHashId,
        locale,
        onDownload,
        onPreview,
        onShare,
        onLocate,
        resolveTreeLeafFileOptions
    ]);
    var handleLoadData = useRefFunction(function(treeNode) {
        var k = String(treeNode.key);
        var source = nodeMap.get(k);
        if (!source) {
            return Promise.resolve();
        }
        if (source.isLeaf === true) {
            return Promise.resolve();
        }
        if (source.isLeaf === undefined && (!source.children || source.children.length === 0)) {
            return Promise.resolve();
        }
        if (source.children && source.children.length > 0) {
            return Promise.resolve();
        }
        // 须让 `Promise` 在失败时 reject，以便 rc-tree 不将 key 记为已加载，从而可再次展开重试
        return Promise.resolve(onLoadChildrenRef(source)).then(function(loaded) {
            var children = loaded !== null && loaded !== void 0 ? loaded : [];
            setInnerTree(function(prev) {
                return replaceNodeChildren(prev, k, children);
            });
        }).catch(function(error) {
            console.error('Failed to load tree children:', error);
            // 返回 reject 以便 rc-tree 不将 key 记为已加载，允许重试
            throw error;
        });
    });
    var handleSelect = useRefFunction(function(_keys, info) {
        if (!info.selected) return;
        var k = String(info.node.key);
        var n = nodeMap.get(k);
        if (!n) return;
        onSelect === null || onSelect === void 0 ? void 0 : onSelect(n);
        var file = resolveTreeLeafFile(n, resolveTreeLeafFileOptions);
        if (!file || n.disabled === true) return;
        if (onFileClick) {
            onFileClick(file);
        } else if (onPreview) {
            void onPreview(file);
        }
    });
    var handleExpand = useRefFunction(function(keys) {
        setExpandedKeys(keys);
    });
    var handleTreeIcon = useRefFunction(function(iconProps) {
        var k = String(iconProps.eventKey);
        var n = nodeMap.get(k);
        if (n === null || n === void 0 ? void 0 : n.icon) {
            return /*#__PURE__*/ React.createElement("span", {
                className: classNames("".concat(prefixCls, "-icon"), hashId)
            }, n.icon);
        }
        if (iconProps.isLeaf) {
            var _ref;
            var fileName = (_ref = n === null || n === void 0 ? void 0 : n.name) !== null && _ref !== void 0 ? _ref : '';
            var fileType = getFileType(fileName);
            return /*#__PURE__*/ React.createElement("span", {
                className: classNames("".concat(prefixCls, "-icon"), hashId),
                "aria-hidden": true
            }, getFileTypeIcon(fileType, undefined, fileName));
        }
        return /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-icon"), "".concat(prefixCls, "-icon--folder"), hashId),
            "aria-hidden": true
        }, /*#__PURE__*/ React.createElement(FileFolders, null));
    });
    var emptyNode = typeof emptyRender === 'function' ? emptyRender() : emptyRender;
    var defaultEmpty = /*#__PURE__*/ React.createElement(Empty, {
        image: Empty.PRESENTED_IMAGE_SIMPLE,
        description: (_ref = locale === null || locale === void 0 ? void 0 : locale['workspace.empty']) !== null && _ref !== void 0 ? _ref : '暂无数据'
    });
    var showEmpty = innerTree.length === 0;
    var showFilterNoMatch = innerTree.length > 0 && Boolean(filterKeyword === null || filterKeyword === void 0 ? void 0 : filterKeyword.trim()) && displayTree.length === 0;
    var filterEmptyState = showFilterNoMatch ? expandedSet.size > 0 ? 'expandedNoMatch' : 'rootsNoMatch' : null;
    var filterNoMatchNode = filterEmptyState === null ? null : /*#__PURE__*/ React.createElement(Typography.Text, {
        type: "secondary",
        "data-testid": "file-tree-filter-empty",
        "data-state": filterEmptyState
    }, compileTemplate(filterEmptyState === 'expandedNoMatch' ? (_ref1 = locale === null || locale === void 0 ? void 0 : locale['workspace.treeFilterNoMatchInExpanded']) !== null && _ref1 !== void 0 ? _ref1 : '已在展开目录的已加载内容中查找，未找到与「${keyword}」匹配的结果' : (_ref2 = locale === null || locale === void 0 ? void 0 : locale['workspace.treeFilterNoMatchVisibleRoots']) !== null && _ref2 !== void 0 ? _ref2 : '当前可见列表中未找到与「${keyword}」匹配的文件', {
        keyword: String(filterKeyword !== null && filterKeyword !== void 0 ? filterKeyword : '').trim()
    }));
    var panel = /*#__PURE__*/ React.createElement("div", {
        className: classNames(prefixCls, hashId, className),
        style: style,
        "data-testid": "workspace-file-tree"
    }, showEmpty ? emptyNode !== null && emptyNode !== void 0 ? emptyNode : defaultEmpty : showFilterNoMatch ? filterNoMatchNode : /*#__PURE__*/ React.createElement(Tree, {
        className: classNames("".concat(prefixCls, "-tree"), hashId),
        showLine: showLine,
        showIcon: true,
        blockNode: blockNode,
        expandedKeys: safeExpandedKeys,
        onExpand: handleExpand,
        loadData: handleLoadData,
        onSelect: handleSelect,
        treeData: dataNodes,
        icon: handleTreeIcon
    }));
    return wrapSSR(injectFileItemStyles ? wrapFileItemSSR(panel) : panel);
};
FileTreeComponent.displayName = 'FileTree';
export { FileTreeComponent as FileTree };
