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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
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 _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
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 _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
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);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { ConfigProvider, Image, Input, Spin, Typography } from "antd";
import { ChevronDown as DownIcon, Download as DownloadIcon, Eye as EyeIcon, Locate, ChevronRight as RightIcon, Search, SquareArrowOutUpRight as ShareIcon } from "@sofa-design/icons";
import { Empty } from "antd";
import classNames from "clsx";
import { AnimatePresence, motion } from "framer-motion";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { ActionIconBox } from "../../Components/ActionIconBox";
import { useRefFunction } from "../../Hooks/useRefFunction";
import { I18nContext, compileTemplate } from "../../I18n";
import { formatFileSize, formatLastModified } from "../utils";
import { fileTypeProcessor, isImageFile } from "./FileTypeProcessor";
import { PreviewComponent } from "./PreviewComponent";
import { useFileStyle } from "./style";
import { generateUniqueId, getFileTypeIcon, getGroupIcon } from "./utils";
/** Initial number of files shown per group before "show more" */ var GROUP_INITIAL_PAGE_SIZE = 50;
/** Number of additional files revealed per "show more" click */ var GROUP_PAGE_SIZE_INCREMENT = 100;
// 通用的键盘事件处理函数
var handleKeyboardEvent = function handleKeyboardEvent(e, callback) {
    if (e.key === 'Enter' || e.key === ' ') {
        callback(e);
    }
};
// 通用的下载处理函数
var handleFileDownload = function handleFileDownload(file) {
    var blobUrl = null;
    try {
        // 创建下载链接
        var link = document.createElement('a');
        if (file.url) {
            // 使用url作为下载链接
            link.href = file.url;
        } else if (file.content) {
            // 使用文件内容创建 Blob 对象
            var blob = new Blob([
                file.content
            ], {
                type: 'text/plain'
            });
            blobUrl = URL.createObjectURL(blob);
            link.href = blobUrl;
        } else if (_instanceof(file.file, File) || _instanceof(file.file, Blob)) {
            // 处理 File 或 Blob 对象
            blobUrl = URL.createObjectURL(file.file);
            link.href = blobUrl;
        } else {
            return; // 没有可下载的内容
        }
        // 设置文件名（如果是 File 对象且没有指定文件名，使用 File 对象的名称）
        link.download = file.name || (_instanceof(file.file, File) ? file.file.name : '');
        // 执行下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } finally{
        // 清理 Blob URL
        if (blobUrl) {
            URL.revokeObjectURL(blobUrl);
        }
    }
};
// 通用的默认分享处理函数
var handleDefaultShare = function handleDefaultShare(file) {
    return _async_to_generator(function() {
        var shareUrl, error;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    _state.trys.push([
                        0,
                        2,
                        ,
                        3
                    ]);
                    shareUrl = file.url || file.previewUrl || window.location.href;
                    return [
                        4,
                        navigator.clipboard.writeText(shareUrl)
                    ];
                case 1:
                    _state.sent();
                    return [
                        3,
                        3
                    ];
                case 2:
                    error = _state.sent();
                    return [
                        3,
                        3
                    ];
                case 3:
                    return [
                        2
                    ];
            }
        });
    })();
};
// 确保节点有唯一ID的辅助函数
var ensureNodeWithId = function ensureNodeWithId(node) {
    return _object_spread_props(_object_spread({}, node), {
        id: node.id || generateUniqueId(node)
    });
};
// 获取文件预览源的辅助函数
var getPreviewSource = function getPreviewSource(file) {
    return file.previewUrl || file.url || '';
};
var AccessibleButton = function AccessibleButton(param) {
    var icon = param.icon, onClick = param.onClick, className = param.className, ariaLabel = param.ariaLabel, id = param.id;
    return /*#__PURE__*/ React.createElement("div", {
        id: id,
        className: className,
        onClick: onClick,
        role: "button",
        tabIndex: 0,
        onKeyDown: function onKeyDown(e) {
            return handleKeyboardEvent(e, onClick);
        },
        "aria-label": ariaLabel
    }, icon);
};
var SearchInput = /*#__PURE__*/ React.memo(function(param) {
    var keyword = param.keyword, onChange = param.onChange, searchPlaceholder = param.searchPlaceholder, prefixCls = param.prefixCls, hashId = param.hashId, locale = param.locale;
    var inputRef = useRef(null);
    return /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-search"), hashId)
    }, /*#__PURE__*/ React.createElement(Input, {
        ref: inputRef,
        key: "file-search-input",
        allowClear: true,
        placeholder: searchPlaceholder || (locale === null || locale === void 0 ? void 0 : locale['workspace.searchPlaceholder']) || '搜索文件名',
        prefix: /*#__PURE__*/ React.createElement(Search, null),
        value: keyword !== null && keyword !== void 0 ? keyword : '',
        onChange: function onChange1(e) {
            return onChange === null || onChange === void 0 ? void 0 : onChange(e.target.value);
        }
    }));
});
SearchInput.displayName = 'SearchInput';
// 文件项组件
var FileItemComponent = /*#__PURE__*/ React.memo(function(param) {
    var file = param.file, onClick = param.onClick, onDownload = param.onDownload, onPreview = param.onPreview, onShare = param.onShare, onLocate = param.onLocate, prefixCls = param.prefixCls, hashId = param.hashId, locale = param.locale, _param_bindDomId = param.bindDomId, bindDomId = _param_bindDomId === void 0 ? false : _param_bindDomId;
    // 确保文件有唯一ID
    var fileWithId = ensureNodeWithId(file);
    var fileTypeInfo = fileTypeProcessor.inferFileType(fileWithId);
    // 禁用状态
    var isDisabled = fileWithId.disabled === true;
    var handleClick = function handleClick() {
        // 禁用状态下不响应点击
        if (isDisabled) return;
        // 如果有传入 onClick 事件，优先使用
        if (onClick) {
            onClick(fileWithId);
            return;
        }
        // 如果没有传入 onClick 事件，默认打开预览页面
        if (onPreview) {
            onPreview(fileWithId);
        }
    };
    // 判断是否显示下载按钮：优先使用用户 canDownload；否则当存在 onDownload/url/content/file 时显示
    var showDownloadButton = function() {
        if (fileWithId.canDownload !== undefined) {
            return fileWithId.canDownload;
        }
        return Boolean(onDownload || fileWithId.url || fileWithId.content || fileWithId.file);
    }();
    var handleDownload = function handleDownload(e) {
        e.stopPropagation();
        // 优先使用用户传入的下载方法
        if (onDownload) {
            onDownload(fileWithId);
            return;
        }
        handleFileDownload(fileWithId);
    };
    var handlePreview = function handlePreview(e) {
        e.stopPropagation();
        onPreview === null || onPreview === void 0 ? void 0 : onPreview(fileWithId);
    };
    var handleShare = function handleShare(e) {
        e.stopPropagation();
        // 如果有自定义的分享方法，优先使用
        if (onShare) {
            onShare(fileWithId, {
                anchorEl: e.currentTarget,
                origin: 'list'
            });
            return;
        }
        // 使用默认分享行为
        handleDefaultShare(fileWithId);
    };
    // 判断是否显示预览按钮：
    // 1. 如果用户设置了 canPreview，优先使用用户的设置
    // 2. 如果没有设置，则使用系统默认逻辑：图片类型有 url 就可以预览；其他类型按原有逻辑判断
    var showPreviewButton = function() {
        // 如果用户明确设置了 canPreview，直接使用用户设置
        if (fileWithId.canPreview !== undefined) {
            return fileWithId.canPreview;
        }
        // 否则使用系统默认逻辑
        return onPreview && (isImageFile(fileWithId) ? !!(fileWithId.url || fileWithId.previewUrl) : fileTypeProcessor.processFile(fileWithId).canPreview);
    }();
    var showShareButton = fileWithId.canShare === true;
    var showLocationButton = fileWithId.canLocate === true;
    var handleLocate = function handleLocate(e) {
        e.stopPropagation();
        onLocate === null || onLocate === void 0 ? void 0 : onLocate(fileWithId);
    };
    // 内置操作按钮
    var actionBtnClass = classNames("".concat(prefixCls, "-item-action-btn"), hashId);
    var builtinActions = {
        preview: showPreviewButton ? /*#__PURE__*/ React.createElement(ActionIconBox, {
            key: "preview",
            title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.preview']) || '预览',
            onClick: handlePreview,
            tooltipProps: {
                mouseEnterDelay: 0.3
            },
            className: actionBtnClass
        }, /*#__PURE__*/ React.createElement(EyeIcon, null)) : null,
        locate: showLocationButton ? /*#__PURE__*/ React.createElement(ActionIconBox, {
            key: "locate",
            title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.location']) || '定位',
            onClick: handleLocate,
            tooltipProps: {
                mouseEnterDelay: 0.3
            },
            className: actionBtnClass
        }, /*#__PURE__*/ React.createElement(Locate, null)) : null,
        share: showShareButton ? /*#__PURE__*/ React.createElement(ActionIconBox, {
            key: "share",
            title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.share']) || '分享',
            onClick: handleShare,
            tooltipProps: {
                mouseEnterDelay: 0.3
            },
            className: actionBtnClass
        }, /*#__PURE__*/ React.createElement(ShareIcon, null)) : null,
        download: showDownloadButton ? /*#__PURE__*/ React.createElement(ActionIconBox, {
            key: "download",
            title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.download']) || '下载',
            onClick: handleDownload,
            tooltipProps: {
                mouseEnterDelay: 0.3
            },
            className: actionBtnClass
        }, /*#__PURE__*/ React.createElement(DownloadIcon, null)) : null
    };
    // 自定义渲染上下文
    var renderContext = {
        file: fileWithId,
        prefixCls: prefixCls,
        hashId: hashId,
        disabled: isDisabled,
        actions: builtinActions
    };
    return /*#__PURE__*/ React.createElement(AccessibleButton, {
        icon: /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-item-icon"), hashId)
        }, getFileTypeIcon(fileTypeInfo.fileType, fileWithId.icon, fileWithId.name)), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-item-info"), hashId)
        }, /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-item-name"), hashId)
        }, fileWithId.renderName ? fileWithId.renderName(renderContext) : /*#__PURE__*/ React.createElement(Typography.Text, {
            ellipsis: {
                tooltip: fileWithId.name
            }
        }, fileWithId.name)), (fileWithId.renderDetails || fileTypeInfo.displayType || fileWithId.size || fileWithId.lastModified) && /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-item-details"), hashId)
        }, fileWithId.renderDetails ? fileWithId.renderDetails(renderContext) : /*#__PURE__*/ React.createElement(Typography.Text, {
            type: "secondary",
            ellipsis: true
        }, fileTypeInfo.displayType && /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-item-type"), hashId)
        }, fileTypeInfo.displayType), fileWithId.size && /*#__PURE__*/ React.createElement(React.Fragment, null, fileTypeInfo.displayType && /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-item-separator"), hashId)
        }, "|"), /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-item-size"), hashId)
        }, formatFileSize(fileWithId.size))), fileWithId.lastModified && /*#__PURE__*/ React.createElement(React.Fragment, null, (fileTypeInfo.displayType || fileWithId.size) && /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-item-separator"), hashId)
        }, "|"), /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-item-time"), hashId)
        }, formatLastModified(fileWithId.lastModified)))))), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-item-actions"), hashId),
            onClick: function onClick(e) {
                return e.stopPropagation();
            }
        }, fileWithId.renderActions ? fileWithId.renderActions(renderContext) : !isDisabled ? /*#__PURE__*/ React.createElement(React.Fragment, null, builtinActions.preview, builtinActions.locate, builtinActions.share, builtinActions.download) : null)),
        onClick: handleClick,
        className: classNames("".concat(prefixCls, "-item"), _define_property({}, "".concat(prefixCls, "-item-disabled"), isDisabled), hashId),
        ariaLabel: "".concat((locale === null || locale === void 0 ? void 0 : locale['workspace.file']) || '文件', "：").concat(fileWithId.name),
        id: bindDomId ? fileWithId.id : undefined
    });
});
// 分组标题栏组件
var GroupHeader = /*#__PURE__*/ React.memo(function(param) {
    var group = param.group, onToggle = param.onToggle, onGroupDownload = param.onGroupDownload, prefixCls = param.prefixCls, hashId = param.hashId, locale = param.locale;
    var groupTypeInfo = fileTypeProcessor.inferFileType(group);
    var groupType = group.type || groupTypeInfo.fileType;
    var handleToggle = function handleToggle() {
        onToggle === null || onToggle === void 0 ? void 0 : onToggle(group.id, groupType, !group.collapsed);
    };
    var handleDownload = function handleDownload(e) {
        e.stopPropagation();
        onGroupDownload === null || onGroupDownload === void 0 ? void 0 : onGroupDownload(group.children, groupType);
    };
    var CollapseIcon = group.collapsed ? RightIcon : DownIcon;
    // 获取分组图标
    var groupIcon = getGroupIcon(group, groupType, group.icon);
    // 判断是否显示下载按钮：优先使用用户 canDownload；否则当存在 onGroupDownload 时显示
    var showDownloadButton = function() {
        if (group.canDownload !== undefined) {
            return group.canDownload;
        }
        if (!onGroupDownload) {
            return false;
        }
        // 如果组内所有文件都明确禁止下载，则不显示分组下载
        return group.children.some(function(child) {
            return child.canDownload === true || child.canDownload !== false && Boolean(child.url || child.content || child.file);
        });
    }();
    return /*#__PURE__*/ React.createElement(AccessibleButton, {
        icon: /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-group-header-left"), hashId)
        }, /*#__PURE__*/ React.createElement(CollapseIcon, {
            className: classNames("".concat(prefixCls, "-group-toggle-icon"), hashId)
        }), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-group-type-icon"), hashId)
        }, groupIcon), /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-group-type-name"), hashId)
        }, group.name)), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-group-header-right"), hashId)
        }, /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-group-count"), hashId)
        }, group.children.length), showDownloadButton && /*#__PURE__*/ React.createElement(ActionIconBox, {
            title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.download']) || '下载',
            onClick: handleDownload,
            tooltipProps: {
                mouseEnterDelay: 0.3
            },
            className: classNames("".concat(prefixCls, "-group-action-btn"), hashId)
        }, /*#__PURE__*/ React.createElement(DownloadIcon, null)))),
        onClick: handleToggle,
        className: classNames("".concat(prefixCls, "-group-header"), hashId),
        ariaLabel: "".concat(group.collapsed ? (locale === null || locale === void 0 ? void 0 : locale['workspace.expand']) || '展开' : (locale === null || locale === void 0 ? void 0 : locale['workspace.collapse']) || '收起').concat(group.name).concat((locale === null || locale === void 0 ? void 0 : locale['workspace.group']) || '分组')
    });
});
// 文件分组组件
var FileGroupComponent = /*#__PURE__*/ React.memo(function(param) {
    var group = param.group, onToggle = param.onToggle, onGroupDownload = param.onGroupDownload, onDownload = param.onDownload, onFileClick = param.onFileClick, onPreview = param.onPreview, onShare = param.onShare, onLocate = param.onLocate, prefixCls = param.prefixCls, hashId = param.hashId, locale = param.locale, bindDomId = param.bindDomId;
    var _useState = _sliced_to_array(useState(GROUP_INITIAL_PAGE_SIZE), 2), visibleCount = _useState[0], setVisibleCount = _useState[1];
    // 分组数据变化时重置分页，避免切换数据源后一次性展示过多节点
    useEffect(function() {
        setVisibleCount(GROUP_INITIAL_PAGE_SIZE);
    }, [
        group.id,
        group.children.length
    ]);
    var totalCount = group.children.length;
    var visibleFiles = group.children.slice(0, visibleCount);
    var remainingCount = totalCount - visibleCount;
    var hasMore = remainingCount > 0;
    var handleShowMore = useRefFunction(function(e) {
        e.stopPropagation();
        setVisibleCount(function(prev) {
            return prev + GROUP_PAGE_SIZE_INCREMENT;
        });
    });
    var handleShowMoreKeyDown = useRefFunction(function(e) {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            e.stopPropagation();
            setVisibleCount(function(prev) {
                return prev + GROUP_PAGE_SIZE_INCREMENT;
            });
        }
    });
    var contentVariants = useMemo(function() {
        return {
            expanded: {
                height: 'auto',
                opacity: 1
            },
            collapsed: {
                height: 0,
                opacity: 0
            }
        };
    }, []);
    var contentTransition = useMemo(function() {
        return {
            height: {
                duration: 0.26,
                ease: [
                    0.4,
                    0,
                    0.2,
                    1
                ]
            },
            opacity: {
                duration: 0.2,
                ease: 'linear'
            }
        };
    }, []);
    var showMoreLabel = hasMore ? compileTemplate((locale === null || locale === void 0 ? void 0 : locale['workspace.file.showMore']) || '查看更多（还有 ${count} 个）', {
        count: String(remainingCount)
    }) : (locale === null || locale === void 0 ? void 0 : locale['workspace.file.showMoreFiles']) || '查看更多文件';
    return /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-container--group"), hashId)
    }, /*#__PURE__*/ React.createElement(GroupHeader, {
        group: group,
        onToggle: onToggle,
        onGroupDownload: onGroupDownload,
        prefixCls: prefixCls,
        hashId: hashId,
        locale: locale
    }), /*#__PURE__*/ React.createElement(AnimatePresence, {
        initial: false
    }, !group.collapsed && /*#__PURE__*/ React.createElement(motion.div, {
        key: "group-content",
        variants: contentVariants,
        initial: "collapsed",
        animate: "expanded",
        exit: "collapsed",
        transition: contentTransition,
        className: classNames("".concat(prefixCls, "-group-content"), hashId)
    }, visibleFiles.map(function(file) {
        return /*#__PURE__*/ React.createElement(FileItemComponent, {
            key: file.id,
            file: file,
            onClick: onFileClick,
            onDownload: onDownload,
            onPreview: onPreview,
            onShare: onShare,
            onLocate: onLocate,
            prefixCls: prefixCls,
            hashId: hashId,
            locale: locale,
            bindDomId: !!bindDomId
        });
    }), hasMore && /*#__PURE__*/ React.createElement("div", {
        role: "button",
        tabIndex: 0,
        className: classNames("".concat(prefixCls, "-show-more"), hashId),
        onClick: handleShowMore,
        onKeyDown: handleShowMoreKeyDown,
        "aria-label": showMoreLabel
    }, showMoreLabel))));
});
export var FileComponent = function FileComponent(param) {
    var nodes = param.nodes, onGroupDownload = param.onGroupDownload, onDownload = param.onDownload, onShare = param.onShare, onFileClick = param.onFileClick, onLocate = param.onLocate, onToggleGroup = param.onToggleGroup, onGroupToggle = param.onGroupToggle, onPreview = param.onPreview, onBack = param.onBack, resetKey = param.resetKey, markdownEditorProps = param.markdownEditorProps, customActions = param.customActions, actionRef = param.actionRef, loading = param.loading, loadingRender = param.loadingRender, emptyRender = param.emptyRender, keyword = param.keyword, onChange = param.onChange, _param_showSearch = param.showSearch, showSearch = _param_showSearch === void 0 ? false : _param_showSearch, searchPlaceholder = param.searchPlaceholder, _param_bindDomId = param.bindDomId, bindDomId = _param_bindDomId === void 0 ? false : _param_bindDomId;
    var _useState = _sliced_to_array(useState(null), 2), previewFile = _useState[0], setPreviewFile = _useState[1];
    var _useState1 = _sliced_to_array(useState(null), 2), customPreviewContent = _useState1[0], setCustomPreviewContent = _useState1[1];
    var _useState2 = _sliced_to_array(useState(null), 2), customPreviewHeader = _useState2[0], setCustomPreviewHeader = _useState2[1];
    // 标题区域文件信息覆盖，仅影响展示
    var _useState3 = _sliced_to_array(useState(null), 2), headerFileOverride = _useState3[0], setHeaderFileOverride = _useState3[1];
    var _useState4 = _sliced_to_array(useState({
        visible: false,
        src: ''
    }), 2), imagePreview = _useState4[0], setImagePreview = _useState4[1];
    // 添加内部状态来管理分组的折叠状态
    var _useState5 = _sliced_to_array(useState({}), 2), collapsedGroups = _useState5[0], setCollapsedGroups = _useState5[1];
    // 扁平文件列表（非分组模式）分页状态
    var _useState6 = _sliced_to_array(useState(GROUP_INITIAL_PAGE_SIZE), 2), flatVisibleCount = _useState6[0], setFlatVisibleCount = _useState6[1];
    // nodes 或 keyword 变化时重置扁平列表分页，避免切换数据源后一次性渲染过多节点
    useEffect(function() {
        setFlatVisibleCount(GROUP_INITIAL_PAGE_SIZE);
    }, [
        nodes,
        keyword
    ]);
    // 追踪预览请求的序号，避免异步竞态
    var previewRequestIdRef = useRef(0);
    // 缓存节点 ID，避免每次渲染重新生成（使用 WeakMap 自动清理不再使用的节点）
    var nodeIdCacheRef = useRef(new WeakMap());
    var safeNodes = nodes || [];
    // 使用 ConfigProvider 获取前缀类名
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var locale = useContext(I18nContext).locale;
    var prefixCls = getPrefixCls('workspace-file');
    var _useFileStyle = useFileStyle(prefixCls), wrapSSR = _useFileStyle.wrapSSR, hashId = _useFileStyle.hashId;
    // 确保节点有稳定的唯一 ID（使用缓存）
    var ensureNodeWithStableId = useRefFunction(function(node) {
        if (node.id) return _object_spread({}, node);
        // 尝试从缓存获取 ID
        var cachedId = nodeIdCacheRef.current.get(node);
        if (!cachedId) {
            // 生成新 ID 并缓存
            cachedId = generateUniqueId(node);
            nodeIdCacheRef.current.set(node, cachedId);
        }
        return _object_spread_props(_object_spread({}, node), {
            id: cachedId
        });
    });
    // 返回列表（供预览页调用）
    var handleBackToList = useRefFunction(function() {
        // 使进行中的预览请求失效
        previewRequestIdRef.current++;
        setPreviewFile(null);
        setCustomPreviewContent(null);
        setCustomPreviewHeader(null);
        setHeaderFileOverride(null);
    });
    // 监听 resetKey 变化，重置预览状态
    useEffect(function() {
        if (resetKey !== undefined && previewFile) {
            // 当 resetKey 变化且当前处于预览状态时，重置预览状态
            handleBackToList();
        }
    }, [
        resetKey
    ]);
    // 监听 nodes 变化，同步更新 previewFile
    useEffect(function() {
        if (!previewFile) return;
        // 在所有节点中查找与当前预览文件匹配的文件
        var findUpdatedFile = function findUpdatedFile1(nodesList) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = nodesList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var node = _step.value;
                    if ('children' in node) {
                        // 分组节点，递归查找子节点
                        var found = findUpdatedFile(node.children);
                        if (found) return found;
                    } else {
                        // 文件节点，比较 ID 或文件引用
                        if (node.id && node.id === previewFile.id || node.name === previewFile.name && node.type === previewFile.type) {
                            return node;
                        }
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
            return null;
        };
        var updatedFile = findUpdatedFile(safeNodes);
        // 如果找到了更新的文件，更新 previewFile
        if (updatedFile) {
            setPreviewFile(updatedFile);
        }
    }, [
        nodes
    ]);
    // 处理分组折叠/展开
    var handleToggleGroup = useRefFunction(function(groupId, type, collapsed) {
        // 更新内部状态，使用 groupId 作为 key
        setCollapsedGroups(function(prev) {
            return _object_spread_props(_object_spread({}, prev), _define_property({}, groupId, collapsed));
        });
        // 优先使用新的事件名，保持向后兼容
        if (onGroupToggle) {
            onGroupToggle(type, collapsed);
        } else if (onToggleGroup) {
            onToggleGroup(type, collapsed);
        }
    });
    // 包装后的返回逻辑，允许外部拦截
    var handleBack = useRefFunction(function() {
        return _async_to_generator(function() {
            var result, _;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!previewFile) return [
                            3,
                            4
                        ];
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            3,
                            ,
                            4
                        ]);
                        return [
                            4,
                            onBack === null || onBack === void 0 ? void 0 : onBack(previewFile)
                        ];
                    case 2:
                        result = _state.sent();
                        if (result === false) return [
                            2
                        ];
                        return [
                            3,
                            4
                        ];
                    case 3:
                        _ = _state.sent();
                        return [
                            3,
                            4
                        ];
                    case 4:
                        handleBackToList();
                        return [
                            2
                        ];
                }
            });
        })();
    });
    // 预览页面的下载（供预览页调用）
    var handleDownloadInPreview = useRefFunction(function(file) {
        // 优先使用用户传入的下载方法
        if (onDownload) {
            onDownload(file);
            return;
        }
        handleFileDownload(file);
    });
    // 预览文件处理
    var handlePreview = useRefFunction(function(file) {
        return _async_to_generator(function() {
            var currentCallId, previewData, content, err, previewSrc;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!onPreview) return [
                            3,
                            4
                        ];
                        currentCallId = ++previewRequestIdRef.current;
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            3,
                            ,
                            4
                        ]);
                        return [
                            4,
                            onPreview(file)
                        ];
                    case 2:
                        previewData = _state.sent();
                        if (previewRequestIdRef.current !== currentCallId) return [
                            2
                        ];
                        // 当用户返回 false：阻止内部预览逻辑，交由外部处理（如自定义弹窗）
                        if (previewData === false) {
                            setCustomPreviewContent(null);
                            setCustomPreviewHeader(null);
                            setPreviewFile(null);
                            return [
                                2
                            ];
                        }
                        // 只有当返回结果不是 false 时，才设置预览文件并处理预览数据
                        if (previewData) {
                            // 区分返回类型：ReactNode -> 自定义内容；FileNode -> 新文件预览
                            if (/*#__PURE__*/ React.isValidElement(previewData) || typeof previewData === 'string' || typeof previewData === 'number' || typeof previewData === 'boolean') {
                                setPreviewFile(file);
                                content = /*#__PURE__*/ React.isValidElement(previewData) ? /*#__PURE__*/ React.cloneElement(previewData, {
                                    setPreviewHeader: function setPreviewHeader(header) {
                                        return setCustomPreviewHeader(header);
                                    },
                                    back: handleBackToList,
                                    download: function download() {
                                        return handleDownloadInPreview(file);
                                    },
                                    share: function share() {
                                        if (onShare) {
                                            // 为保持回调参数签名一致，显式传入第二个参数为 undefined
                                            onShare(file, undefined);
                                        } else {
                                            handleDefaultShare(file);
                                        }
                                    }
                                }) : previewData;
                                setCustomPreviewHeader(null);
                                setCustomPreviewContent(content);
                            } else if ((typeof previewData === "undefined" ? "undefined" : _type_of(previewData)) === 'object' && previewData !== null && 'name' in previewData) {
                                setCustomPreviewContent(null);
                                setCustomPreviewHeader(null);
                                setPreviewFile(previewData);
                            } else {
                                setCustomPreviewContent(null);
                                setCustomPreviewHeader(null);
                                setPreviewFile(file);
                            }
                            return [
                                2
                            ];
                        }
                        // previewData 为 undefined 或 null，使用默认预览
                        setCustomPreviewContent(null);
                        setPreviewFile(file);
                        return [
                            2
                        ];
                    case 3:
                        err = _state.sent();
                        if (previewRequestIdRef.current !== currentCallId) return [
                            2
                        ];
                        setCustomPreviewContent(null);
                        setPreviewFile(file);
                        return [
                            2
                        ];
                    case 4:
                        // 使用组件库内部的预览逻辑
                        if (isImageFile(file)) {
                            previewSrc = getPreviewSource(file);
                            setImagePreview({
                                visible: true,
                                src: previewSrc
                            });
                            return [
                                2
                            ];
                        }
                        setCustomPreviewContent(null);
                        setPreviewFile(file);
                        return [
                            2
                        ];
                }
            });
        })();
    });
    // 通过 actionRef 暴露可编程接口
    React.useEffect(function() {
        if (!actionRef) return;
        actionRef.current = {
            openPreview: function openPreview(file) {
                var fileWithId = ensureNodeWithStableId(file);
                void handlePreview(fileWithId);
            },
            backToList: function backToList() {
                handleBackToList();
            },
            updatePreviewHeader: function updatePreviewHeader(partial) {
                setHeaderFileOverride(function(prev) {
                    return _object_spread({}, prev || {}, partial);
                });
            }
        };
        return function() {
            actionRef.current = null;
        };
    }, [
        actionRef,
        handlePreview,
        handleBackToList
    ]);
    var hasKeyword = Boolean((keyword !== null && keyword !== void 0 ? keyword : '').trim());
    // 渲染搜索框组件 - 确保在所有情况下都保持一致
    var renderSearchInput = useRefFunction(function() {
        if (!showSearch) return null;
        return /*#__PURE__*/ React.createElement(SearchInput, {
            keyword: keyword,
            onChange: onChange,
            searchPlaceholder: searchPlaceholder,
            prefixCls: prefixCls,
            hashId: hashId,
            locale: locale
        });
    });
    // 渲染空状态内容
    var renderEmptyContent = useRefFunction(function() {
        if (hasKeyword) {
            return /*#__PURE__*/ React.createElement(Typography.Text, {
                type: "secondary"
            }, ((locale === null || locale === void 0 ? void 0 : locale['workspace.noResultsFor']) || "未找到与「".concat(keyword, "」匹配的结果")).replace('${keyword}', String(keyword)));
        }
        if (typeof emptyRender === 'function') {
            return emptyRender();
        }
        return emptyRender !== null && emptyRender !== void 0 ? emptyRender : /*#__PURE__*/ React.createElement(Empty, {
            description: (locale === null || locale === void 0 ? void 0 : locale['workspace.empty']) || 'No data'
        });
    });
    var handleFlatShowMore = useRefFunction(function() {
        setFlatVisibleCount(function(prev) {
            return prev + GROUP_PAGE_SIZE_INCREMENT;
        });
    });
    var handleFlatShowMoreKeyDown = useRefFunction(function(e) {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleFlatShowMore();
        }
    });
    // 渲染文件内容
    var renderFileContent = useRefFunction(function() {
        if ((!nodes || nodes.length === 0) && !loading) {
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-empty"), hashId)
            }, renderEmptyContent());
        }
        if (safeNodes.length === 0) {
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-empty"), hashId)
            }, renderEmptyContent());
        }
        // Determine whether this is a purely flat list (no groups) so we can paginate
        var isFlat = safeNodes.every(function(n) {
            return !('children' in n);
        });
        var nodesToRender = isFlat ? safeNodes.slice(0, flatVisibleCount) : safeNodes;
        var flatRemaining = isFlat ? safeNodes.length - flatVisibleCount : 0;
        var flatHasMore = flatRemaining > 0;
        var items = nodesToRender.map(function(node) {
            var nodeWithId = ensureNodeWithStableId(node);
            if ('children' in nodeWithId) {
                var _collapsedGroups_nodeWithId_id;
                // 分组节点，使用内部状态覆盖外部的 collapsed 属性
                var groupNode = _object_spread_props(_object_spread({}, nodeWithId), {
                    collapsed: (_collapsedGroups_nodeWithId_id = collapsedGroups[nodeWithId.id]) !== null && _collapsedGroups_nodeWithId_id !== void 0 ? _collapsedGroups_nodeWithId_id : nodeWithId.collapsed,
                    // 确保子节点也有唯一ID
                    children: nodeWithId.children.map(ensureNodeWithStableId)
                });
                return /*#__PURE__*/ React.createElement(FileGroupComponent, {
                    key: nodeWithId.id,
                    group: groupNode,
                    onToggle: handleToggleGroup,
                    onGroupDownload: onGroupDownload,
                    onDownload: onDownload,
                    onFileClick: onFileClick,
                    onPreview: handlePreview,
                    onShare: onShare,
                    onLocate: onLocate,
                    prefixCls: prefixCls,
                    hashId: hashId,
                    locale: locale,
                    bindDomId: bindDomId
                });
            }
            // 文件节点
            return /*#__PURE__*/ React.createElement(FileItemComponent, {
                key: nodeWithId.id,
                file: nodeWithId,
                onClick: onFileClick,
                onDownload: onDownload,
                onShare: onShare,
                onPreview: handlePreview,
                onLocate: onLocate,
                prefixCls: prefixCls,
                hashId: hashId,
                locale: locale,
                bindDomId: bindDomId
            });
        });
        if (!flatHasMore) return items;
        var flatShowMoreLabel = compileTemplate((locale === null || locale === void 0 ? void 0 : locale['workspace.file.showMore']) || '查看更多（还有 ${count} 个）', {
            count: String(flatRemaining)
        });
        return /*#__PURE__*/ React.createElement(React.Fragment, null, items, /*#__PURE__*/ React.createElement("div", {
            role: "button",
            tabIndex: 0,
            className: classNames("".concat(prefixCls, "-show-more"), hashId),
            onClick: handleFlatShowMore,
            onKeyDown: handleFlatShowMoreKeyDown,
            "aria-label": flatShowMoreLabel
        }, flatShowMoreLabel));
    });
    // 图片预览组件
    var ImagePreviewComponent = /*#__PURE__*/ React.createElement(Image, {
        className: classNames("".concat(prefixCls, "-hidden-image"), hashId),
        src: imagePreview.src,
        preview: {
            visible: imagePreview.visible,
            onVisibleChange: function onVisibleChange(visible) {
                setImagePreview(function(prev) {
                    return _object_spread_props(_object_spread({}, prev), {
                        visible: visible
                    });
                });
            }
        }
    });
    // 如果正在预览文件，显示预览组件
    if (previewFile) {
        return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(PreviewComponent, {
            file: previewFile,
            onBack: handleBack,
            onDownload: handleDownloadInPreview,
            onShare: function onShare1(file, options) {
                if (onShare) {
                    onShare(file, {
                        anchorEl: options === null || options === void 0 ? void 0 : options.anchorEl,
                        origin: 'preview'
                    });
                } else {
                    handleDefaultShare(file);
                }
            },
            onLocate: onLocate,
            customContent: customPreviewContent || undefined,
            customHeader: customPreviewHeader || undefined,
            customActions: typeof customActions === 'function' ? customActions(previewFile) : customActions,
            headerFileOverride: headerFileOverride || undefined,
            markdownEditorProps: markdownEditorProps
        }), ImagePreviewComponent);
    }
    // 统一的渲染逻辑 - 确保搜索框位置稳定
    return wrapSSR(/*#__PURE__*/ React.createElement(React.Fragment, null, loading && loadingRender ? // 使用自定义loading渲染函数
    /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-container"), hashId),
        "data-testid": "file-component"
    }, renderSearchInput(), loadingRender()) : // 使用默认的Spin组件
    /*#__PURE__*/ React.createElement(Spin, {
        spinning: !!loading
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-container"), hashId),
        "data-testid": "file-component"
    }, renderSearchInput(), renderFileContent())), ImagePreviewComponent));
};
