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 _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);
}
import { ApartmentOutlined, BarsOutlined } from "@ant-design/icons";
import { Language, ListTodo, MousePointerClick, X } from "@sofa-design/icons";
import { ConfigProvider, Segmented } from "antd";
import classNames from "clsx";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { ActionIconBox } from "../Components/ActionIconBox";
import { I18nContext } from "../I18n";
import Browser from "./Browser";
import { File, FileTree } from "./File";
import { RealtimeFollowList } from "./RealtimeFollow";
import { useWorkspaceStyle } from "./style";
import { TaskList } from "./Task";
import { WorkspaceTabCountDigits } from "./WorkspaceTabCountDigits";
import { isFileWorkspacePanel, isWorkspacePanelType, isWorkspaceSegmentedDividerKey, markWorkspacePanel, normalizeTabKey, resolveWorkspacePanelType, WORKSPACE_SEGMENTED_DIVIDER_KEY } from "./workspacePanel";
export { markWorkspacePanel, WORKSPACE_PANEL_TYPE, WORKSPACE_SEGMENTED_DIVIDER_KEY } from "./workspacePanel";
var PANEL_TYPES = {
    REALTIME: 'realtime',
    BROWSER: 'browser',
    TASK: 'task',
    FILE: 'file',
    FILE_TREE: 'fileTree',
    CUSTOM: 'custom'
};
var DEFAULT_CONFIG = function DEFAULT_CONFIG(locale) {
    var _obj;
    return _obj = {}, _define_property(_obj, PANEL_TYPES.REALTIME, {
        key: PANEL_TYPES.REALTIME,
        icon: /*#__PURE__*/ React.createElement(MousePointerClick, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.realtimeFollow']) || '实时跟随',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.realtimeFollow']) || '实时跟随'
    }), _define_property(_obj, PANEL_TYPES.BROWSER, {
        key: PANEL_TYPES.BROWSER,
        icon: /*#__PURE__*/ React.createElement(Language, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.browser']) || '浏览器',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.browser']) || '浏览器'
    }), _define_property(_obj, PANEL_TYPES.TASK, {
        key: PANEL_TYPES.TASK,
        icon: /*#__PURE__*/ React.createElement(ListTodo, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.task']) || '任务',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.task']) || '任务'
    }), _define_property(_obj, PANEL_TYPES.FILE, {
        key: PANEL_TYPES.FILE,
        icon: /*#__PURE__*/ React.createElement(BarsOutlined, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file']) || '文件',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.file']) || '文件'
    }), _define_property(_obj, PANEL_TYPES.FILE_TREE, {
        key: PANEL_TYPES.FILE_TREE,
        icon: /*#__PURE__*/ React.createElement(ApartmentOutlined, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.fileTree']) || '文件树',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.fileTree']) || '文件树'
    }), _define_property(_obj, PANEL_TYPES.CUSTOM, {
        key: PANEL_TYPES.CUSTOM,
        icon: null,
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.custom']) || '自定义',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.custom']) || '自定义'
    }), _obj;
};
var resolveTabConfig = function resolveTabConfig(tab, defaultConfig, index) {
    var _ref;
    var customKey = normalizeTabKey(tab === null || tab === void 0 ? void 0 : tab.key);
    var baseKey = customKey && !isWorkspaceSegmentedDividerKey(customKey) ? customKey : defaultConfig.key + (index !== undefined ? "-".concat(index) : '');
    return {
        key: baseKey,
        icon: (_ref = tab === null || tab === void 0 ? void 0 : tab.icon) !== null && _ref !== void 0 ? _ref : defaultConfig.icon,
        title: (tab === null || tab === void 0 ? void 0 : tab.title) || defaultConfig.label,
        count: typeof (tab === null || tab === void 0 ? void 0 : tab.count) === 'number' && Number.isFinite(tab.count) ? tab.count : undefined
    };
};
var flattenWorkspaceChildren = function flattenWorkspaceChildren1(nodes) {
    var result = [];
    React.Children.forEach(nodes, function(child) {
        if (!/*#__PURE__*/ React.isValidElement(child)) {
            return;
        }
        if (child.type === React.Fragment) {
            flattenWorkspaceChildren(child.props.children).forEach(function(nested) {
                return result.push(nested);
            });
            return;
        }
        result.push(child);
    });
    return result;
};
var ensureUniqueTabKey = function ensureUniqueTabKey(key, usedKeys, fallbackSeed) {
    if (!usedKeys.has(key)) {
        usedKeys.add(key);
        return key;
    }
    var candidate = "".concat(key, "-").concat(fallbackSeed);
    var suffix = 1;
    while(usedKeys.has(candidate)){
        candidate = "".concat(key, "-").concat(fallbackSeed, "-").concat(suffix);
        suffix += 1;
    }
    usedKeys.add(candidate);
    return candidate;
};
var RealtimeComponent = function RealtimeComponent(param) {
    var data = param.data;
    return data ? /*#__PURE__*/ React.createElement(RealtimeFollowList, {
        data: data
    }) : null;
};
var BrowserComponent = function BrowserComponent(props) {
    return /*#__PURE__*/ React.createElement(Browser, props);
};
var TaskComponent = function TaskComponent(param) {
    var data = param.data, onItemClick = param.onItemClick;
    return data ? /*#__PURE__*/ React.createElement(TaskList, {
        data: data,
        onItemClick: onItemClick
    }) : null;
};
var FileComponent = function FileComponent(props) {
    return /*#__PURE__*/ React.createElement(File, props);
};
var FileTreeComponent = function FileTreeComponent(props) {
    return /*#__PURE__*/ React.createElement(FileTree, props);
};
var CustomComponent = function CustomComponent(param) {
    var children = param.children;
    return children || null;
};
var resolveChildPanelType = function resolveChildPanelType(child) {
    var fromProps = child.props.panelType;
    if (fromProps !== null && fromProps !== undefined) {
        return isWorkspacePanelType(fromProps) ? fromProps : resolveWorkspacePanelType(child.type);
    }
    return resolveWorkspacePanelType(child.type);
};
var isValidReactPanelType = function isValidReactPanelType(type) {
    return typeof type === 'function' || (typeof type === "undefined" ? "undefined" : _type_of(type)) === 'object';
};
var pickFallbackTabKey = function pickFallbackTabKey(tabs, preferredKey) {
    var _ref;
    var _tabs_;
    var normalizedPreferred = normalizeTabKey(preferredKey);
    if (normalizedPreferred && tabs.some(function(tab) {
        return tab.key === normalizedPreferred;
    })) {
        return normalizedPreferred;
    }
    return (_ref = (_tabs_ = tabs[0]) === null || _tabs_ === void 0 ? void 0 : _tabs_.key) !== null && _ref !== void 0 ? _ref : '';
};
var shouldResetFilePreview = function shouldResetFilePreview(fromKey, toKey, tabs) {
    if (!fromKey || fromKey === toKey) {
        return false;
    }
    var fromTab = tabs.find(function(tab) {
        return tab.key === fromKey;
    });
    if (!fromTab || !isFileWorkspacePanel(fromTab.componentType)) {
        return false;
    }
    var toTab = tabs.find(function(tab) {
        return tab.key === toKey;
    });
    if (!toTab) {
        return true;
    }
    if (!isFileWorkspacePanel(toTab.componentType)) {
        return true;
    }
    return fromTab.key !== toTab.key;
};
/**
 * 工作空间组件
 * 提供多标签页界面，支持实时跟随、浏览器、任务、文件等功能模块
 */ var Workspace = function Workspace(param) {
    var activeTabKey = param.activeTabKey, defaultActiveTabKey = param.defaultActiveTabKey, onTabChange = param.onTabChange, _param_notifyOnInvalidActiveTabKey = param.notifyOnInvalidActiveTabKey, notifyOnInvalidActiveTabKey = _param_notifyOnInvalidActiveTabKey === void 0 ? true : _param_notifyOnInvalidActiveTabKey, _param_preserveFilePreviewOnTabChange = param.preserveFilePreviewOnTabChange, preserveFilePreviewOnTabChange = _param_preserveFilePreviewOnTabChange === void 0 ? false : _param_preserveFilePreviewOnTabChange, style = param.style, className = param.className, title = param.title, onClose = param.onClose, children = param.children, emptyContent = param.emptyContent, _param_pure = param.pure, pure = _param_pure === void 0 ? false : _param_pure, headerExtra = param.headerExtra;
    var _ref;
    var _availableTabs_find, _availableTabs_find1;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var locale = useContext(I18nContext).locale;
    var prefixCls = getPrefixCls('workspace');
    var _useWorkspaceStyle = useWorkspaceStyle(prefixCls), wrapSSR = _useWorkspaceStyle.wrapSSR, hashId = _useWorkspaceStyle.hashId;
    var containerRef = useRef(null);
    var _useState = _sliced_to_array(useState(0), 2), segmentedKey = _useState[0], setSegmentedKey = _useState[1];
    var _useState1 = _sliced_to_array(useState(0), 2), resetKey = _useState1[0], setResetKey = _useState1[1];
    var displayTitle = title !== null && title !== void 0 ? title : (locale === null || locale === void 0 ? void 0 : locale['workspace.title']) || 'Workspace';
    var defaultConfig = useMemo(function() {
        return DEFAULT_CONFIG(locale);
    }, [
        locale
    ]);
    var _useState2 = _sliced_to_array(useState(function() {
        return defaultActiveTabKey !== null && defaultActiveTabKey !== void 0 ? defaultActiveTabKey : '';
    }), 2), internalActiveTab = _useState2[0], setInternalActiveTab = _useState2[1];
    var _useMemo = useMemo(function() {
        var _keys_;
        var panelEntries = [];
        var usedTabKeys = new Set();
        flattenWorkspaceChildren(children).forEach(function(child, index) {
            if (!isValidReactPanelType(child.type)) {
                return;
            }
            var wType = resolveChildPanelType(child);
            if (!wType || !defaultConfig[wType]) {
                return;
            }
            var tabConfig = resolveTabConfig(child.props.tab, defaultConfig[wType], wType === PANEL_TYPES.CUSTOM ? index : undefined);
            var uniqueKey = ensureUniqueTabKey(tabConfig.key, usedTabKeys, String(index));
            panelEntries.push({
                wType: wType,
                child: child,
                tabConfig: _object_spread_props(_object_spread({}, tabConfig), {
                    key: uniqueKey
                })
            });
        });
        var keys = panelEntries.map(function(e) {
            return e.tabConfig.key;
        });
        var normalizedActiveTabKey = normalizeTabKey(activeTabKey);
        var normalizedInternalTab = normalizeTabKey(internalActiveTab);
        var isControlled = activeTabKey !== undefined;
        var effectiveKeyForReset = isControlled && keys.includes(normalizedActiveTabKey) ? normalizedActiveTabKey : normalizedInternalTab && keys.includes(normalizedInternalTab) ? normalizedInternalTab : (_keys_ = keys[0]) !== null && _keys_ !== void 0 ? _keys_ : '';
        var firstRealtimeIndex = panelEntries.findIndex(function(e) {
            return e.wType === PANEL_TYPES.REALTIME;
        });
        var tabs = panelEntries.map(function(entry) {
            var wType = entry.wType, child = entry.child, tabConfig = entry.tabConfig;
            var key = tabConfig.key;
            var shouldPassResetKey = isFileWorkspacePanel(wType) && key === effectiveKeyForReset;
            return {
                key: key,
                icon: tabConfig.icon,
                componentType: wType,
                label: /*#__PURE__*/ React.createElement("div", {
                    className: classNames("".concat(prefixCls, "-tab-item"), hashId)
                }, /*#__PURE__*/ React.createElement("span", {
                    className: classNames("".concat(prefixCls, "-tab-title"), hashId)
                }, tabConfig.title), tabConfig.count !== undefined && /*#__PURE__*/ React.createElement("span", {
                    className: classNames("".concat(prefixCls, "-tab-count"), hashId),
                    "data-testid": "workspace-tab-count--".concat(tabConfig.key)
                }, /*#__PURE__*/ React.createElement(WorkspaceTabCountDigits, {
                    tabKey: tabConfig.key,
                    value: tabConfig.count,
                    prefixCls: prefixCls,
                    hashId: hashId
                }))),
                content: isValidReactPanelType(child.type) ? /*#__PURE__*/ React.createElement(child.type, _object_spread({}, child.props, shouldPassResetKey ? {
                    resetKey: resetKey
                } : {})) : null
            };
        });
        var options = [];
        for(var i = 0; i < tabs.length; i += 1){
            var tab = tabs[i];
            options.push({
                label: tab.label,
                value: tab.key,
                icon: tab.icon
            });
            var isFirstRealtime = firstRealtimeIndex === i && tab.componentType === PANEL_TYPES.REALTIME;
            if (isFirstRealtime && tabs.length > 1) {
                options.push({
                    label: '',
                    value: WORKSPACE_SEGMENTED_DIVIDER_KEY,
                    disabled: true
                });
            }
        }
        return {
            availableTabs: tabs,
            segmentedOptions: options
        };
    }, [
        children,
        defaultConfig,
        hashId,
        prefixCls,
        resetKey,
        activeTabKey,
        internalActiveTab
    ]), availableTabs = _useMemo.availableTabs, segmentedOptions = _useMemo.segmentedOptions;
    useEffect(function() {
        if (!availableTabs.length) return;
        var isControlled = activeTabKey !== undefined;
        var currentKey = normalizeTabKey(isControlled ? activeTabKey : internalActiveTab);
        var fallbackKey = pickFallbackTabKey(availableTabs, isControlled ? undefined : defaultActiveTabKey);
        if (!currentKey || !availableTabs.some(function(tab) {
            return tab.key === currentKey;
        })) {
            if (!isControlled && fallbackKey) {
                setInternalActiveTab(fallbackKey);
            }
            if (notifyOnInvalidActiveTabKey && fallbackKey && fallbackKey !== currentKey) {
                onTabChange === null || onTabChange === void 0 ? void 0 : onTabChange(fallbackKey);
            }
        } else if (isControlled && currentKey !== normalizeTabKey(internalActiveTab)) {
            setInternalActiveTab(currentKey);
        }
    }, [
        availableTabs,
        activeTabKey,
        internalActiveTab,
        onTabChange,
        defaultActiveTabKey,
        notifyOnInvalidActiveTabKey
    ]);
    // 监听容器宽度变化，强制 Segmented 重新渲染
    useEffect(function() {
        if (!containerRef.current) return;
        var el = containerRef.current;
        var lastWidth = el.getBoundingClientRect().width;
        var observer = new ResizeObserver(function(entries) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = entries[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var entry = _step.value;
                    var width = entry.contentRect.width;
                    if (width > 0 && lastWidth === 0) {
                        setSegmentedKey(function(k) {
                            return k + 1;
                        });
                    }
                    lastWidth = width;
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
        });
        observer.observe(el);
        return function() {
            return observer.disconnect();
        };
    }, []);
    var resolvedActiveKey = normalizeTabKey(activeTabKey !== null && activeTabKey !== void 0 ? activeTabKey : internalActiveTab);
    var currentActiveTab = (_ref = (_availableTabs_find = availableTabs.find(function(tab) {
        return tab.key === resolvedActiveKey;
    })) === null || _availableTabs_find === void 0 ? void 0 : _availableTabs_find.key) !== null && _ref !== void 0 ? _ref : pickFallbackTabKey(availableTabs, defaultActiveTabKey);
    var handleTabChange = function handleTabChange(key) {
        var tabKey = normalizeTabKey(key);
        if (!tabKey || isWorkspaceSegmentedDividerKey(tabKey)) {
            return;
        }
        if (!availableTabs.some(function(tab) {
            return tab.key === tabKey;
        })) {
            return;
        }
        if (tabKey === currentActiveTab) {
            return;
        }
        var previousKey = currentActiveTab;
        if (activeTabKey === undefined) {
            setInternalActiveTab(tabKey);
        }
        if (!preserveFilePreviewOnTabChange && shouldResetFilePreview(previousKey, tabKey, availableTabs)) {
            setResetKey(function(prev) {
                return prev + 1;
            });
        }
        onTabChange === null || onTabChange === void 0 ? void 0 : onTabChange(tabKey);
    };
    if (!availableTabs.length) {
        return emptyContent !== null && emptyContent !== void 0 ? emptyContent : null;
    }
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        className: classNames(prefixCls, _define_property({}, "".concat(prefixCls, "-pure"), pure), className, hashId),
        style: style,
        "data-testid": "workspace"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header"), hashId),
        "data-testid": "workspace-header"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-title"), hashId),
        "data-testid": "workspace-title"
    }, displayTitle), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header-right"), hashId)
    }, headerExtra, onClose && /*#__PURE__*/ React.createElement(ActionIconBox, {
        className: classNames("".concat(prefixCls, "-close"), hashId),
        onClick: onClose,
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.closeWorkspace']) || '关闭工作空间',
        "data-testid": "workspace-close"
    }, /*#__PURE__*/ React.createElement(X, null)))), availableTabs.length > 1 && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-tabs"), hashId),
        "data-testid": "workspace-tabs"
    }, /*#__PURE__*/ React.createElement(Segmented, {
        key: segmentedKey,
        className: classNames("".concat(prefixCls, "-segmented"), hashId),
        options: segmentedOptions,
        value: currentActiveTab,
        onChange: handleTabChange,
        block: true,
        "data-testid": "workspace-segmented"
    })), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-content"), hashId),
        "data-testid": "workspace-content"
    }, (_availableTabs_find1 = availableTabs.find(function(tab) {
        return tab.key === currentActiveTab;
    })) === null || _availableTabs_find1 === void 0 ? void 0 : _availableTabs_find1.content)));
};
Workspace.Realtime = markWorkspacePanel(RealtimeComponent, PANEL_TYPES.REALTIME);
Workspace.Browser = markWorkspacePanel(BrowserComponent, PANEL_TYPES.BROWSER);
Workspace.Task = markWorkspacePanel(TaskComponent, PANEL_TYPES.TASK);
Workspace.File = markWorkspacePanel(FileComponent, PANEL_TYPES.FILE);
Workspace.FileTree = markWorkspacePanel(FileTreeComponent, PANEL_TYPES.FILE_TREE);
Workspace.Custom = markWorkspacePanel(CustomComponent, PANEL_TYPES.CUSTOM);
export * from "./File";
export default Workspace;
