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 { ArrowLeft, Locate, Search } from "@sofa-design/icons";
import { Avatar, Button, ConfigProvider, Empty, Image, List, Spin, Tag, Tooltip } from "antd";
import classNames from "clsx";
import React, { useContext, useMemo, useState } from "react";
import { ActionIconBox } from "../../Components/ActionIconBox";
import { I18nContext, compileTemplate } from "../../I18n";
import { useBrowserStyle } from "./style";
export var RESULT_COUNT_TAG_STYLE = {
    height: 20,
    background: 'var(--color-gray-control-fill-active)',
    borderRadius: 200,
    display: 'flex',
    alignItems: 'center',
    font: 'var(--font-text-number-xs)',
    color: 'var(--color-gray-text-secondary)',
    padding: '2px'
};
export var SUGGESTION_ITEM_STYLE = {
    padding: '4px',
    margin: '4px 0',
    cursor: 'pointer'
};
var renderSiteAvatar = function renderSiteAvatar(site, icon) {
    if (icon) {
        return /*#__PURE__*/ React.createElement(Image, {
            src: icon,
            width: 20,
            height: 20,
            preview: false,
            style: {
                borderRadius: 4
            },
            alt: site
        });
    }
    var letter = (site[0] || 'W').toUpperCase();
    return /*#__PURE__*/ React.createElement(Avatar, {
        size: 20
    }, letter);
};
var useBrowserContext = function useBrowserContext() {
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('browser');
    var _useBrowserStyle = useBrowserStyle(prefixCls), wrapSSR = _useBrowserStyle.wrapSSR, hashId = _useBrowserStyle.hashId;
    return {
        prefixCls: prefixCls,
        wrapSSR: wrapSSR,
        hashId: hashId
    };
};
export var BrowserItemComponent = function BrowserItemComponent(param) {
    var item = param.item, _param_itemStyle = param.itemStyle, itemStyle = _param_itemStyle === void 0 ? SUGGESTION_ITEM_STYLE : _param_itemStyle, className = param.className, onLocate = param.onLocate;
    var _useBrowserContext = useBrowserContext(), prefixCls = _useBrowserContext.prefixCls, wrapSSR = _useBrowserContext.wrapSSR, hashId = _useBrowserContext.hashId;
    var locale = useContext(I18nContext).locale;
    var handleSiteClick = function handleSiteClick() {
        window.open(item.url, '_blank', 'noopener,noreferrer');
    };
    var handleLocate = function handleLocate(e) {
        e.stopPropagation();
        onLocate === null || onLocate === void 0 ? void 0 : onLocate(item);
    };
    return wrapSSR(/*#__PURE__*/ React.createElement(List.Item, {
        className: className,
        style: itemStyle,
        actions: item.canLocate ? [
            /*#__PURE__*/ React.createElement(ActionIconBox, {
                key: "locate",
                title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.location']) || '定位',
                onClick: handleLocate,
                tooltipProps: {
                    mouseEnterDelay: 0.3
                }
            }, /*#__PURE__*/ React.createElement(Locate, null))
        ] : []
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            width: '100%'
        }
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-result-item-title-wrapper"), hashId)
    }, /*#__PURE__*/ React.createElement(Tooltip, {
        title: item.title,
        mouseEnterDelay: 0.5
    }, /*#__PURE__*/ React.createElement("a", {
        href: item.url,
        target: "_blank",
        rel: "noreferrer",
        style: {
            color: 'inherit'
        }
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-result-item-title"), hashId)
    }, item.title)))), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-result-item-site"), hashId),
        onClick: handleSiteClick
    }, renderSiteAvatar(item.site, item.icon), /*#__PURE__*/ React.createElement(Tooltip, {
        title: item.site,
        mouseEnterDelay: 1
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-result-item-site-text"), hashId)
    }, item.site))))));
};
export var BrowserHeader = function BrowserHeader(param) {
    var activeLabel = param.activeLabel, onBack = param.onBack;
    var _useBrowserContext = useBrowserContext(), prefixCls = _useBrowserContext.prefixCls, wrapSSR = _useBrowserContext.wrapSSR, hashId = _useBrowserContext.hashId;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header-left"), hashId)
    }, onBack && /*#__PURE__*/ React.createElement(Button, {
        type: "text",
        icon: /*#__PURE__*/ React.createElement(ArrowLeft, {
            style: {
                color: 'var(--color-gray-text-quaternary)'
            }
        }),
        onClick: onBack
    }), /*#__PURE__*/ React.createElement(Tooltip, {
        title: activeLabel,
        mouseEnterDelay: 0.5
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header-title"), hashId)
    }, activeLabel))));
};
export var BrowserList = function BrowserList(param) {
    var items = param.items, activeLabel = param.activeLabel, onBack = param.onBack, customHeader = param.customHeader, _param_showHeader = param.showHeader, showHeader = _param_showHeader === void 0 ? true : _param_showHeader, countFormatter = param.countFormatter, emptyText = param.emptyText, _param_loading = param.loading, loading = _param_loading === void 0 ? false : _param_loading, loadingText = param.loadingText, onLocate = param.onLocate;
    var _useBrowserContext = useBrowserContext(), prefixCls = _useBrowserContext.prefixCls, wrapSSR = _useBrowserContext.wrapSSR, hashId = _useBrowserContext.hashId;
    var locale = useContext(I18nContext).locale;
    var safeItems = Array.isArray(items) ? items : [];
    var mergedEmptyText = emptyText || locale['browser.noResults'] || 'No results found';
    var mergedLoadingText = loadingText || locale['browser.searching'] || 'Searching...';
    var totalResultsTemplate = locale['browser.totalResults'] || 'Total ${count} results';
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        "data-testid": "browser-list"
    }, /*#__PURE__*/ React.createElement("header", {
        className: classNames("".concat(prefixCls, "-header-wrapper"), hashId),
        style: {
            borderBottom: showHeader ? '1px solid rgba(20, 22, 28, 0.1)' : 'none'
        }
    }, showHeader && (customHeader || /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header"), hashId)
    }, /*#__PURE__*/ React.createElement(BrowserHeader, {
        activeLabel: activeLabel,
        onBack: onBack
    }), /*#__PURE__*/ React.createElement(Tag, {
        style: RESULT_COUNT_TAG_STYLE
    }, typeof countFormatter === 'function' ? countFormatter(safeItems.length) : compileTemplate(totalResultsTemplate, {
        count: String(safeItems.length)
    }))))), /*#__PURE__*/ React.createElement(List, {
        dataSource: safeItems,
        split: false,
        loading: false,
        locale: {
            emptyText: loading && safeItems.length === 0 ? /*#__PURE__*/ React.createElement("div", {
                style: {
                    padding: '48px 0',
                    textAlign: 'center'
                }
            }, /*#__PURE__*/ React.createElement(Spin, null), /*#__PURE__*/ React.createElement("div", {
                style: {
                    marginTop: 8
                }
            }, mergedLoadingText)) : /*#__PURE__*/ React.createElement(Empty, {
                description: mergedEmptyText
            })
        },
        renderItem: function renderItem(item) {
            return /*#__PURE__*/ React.createElement(BrowserItemComponent, {
                key: item.id,
                item: item,
                className: classNames("".concat(prefixCls, "-result-item"), hashId),
                itemStyle: SUGGESTION_ITEM_STYLE,
                onLocate: onLocate
            });
        },
        footer: null
    })));
};
var Browser = function Browser(param) {
    var suggestions = param.suggestions, request = param.request, suggestionIcon = param.suggestionIcon, countFormatter = param.countFormatter, emptyText = param.emptyText, loadingText = param.loadingText, onLocate = param.onLocate;
    var _useState = _sliced_to_array(useState('suggestions'), 2), currentView = _useState[0], setCurrentView = _useState[1];
    var _useState1 = _sliced_to_array(useState(null), 2), activeSuggestion = _useState1[0], setActiveSuggestion = _useState1[1];
    var _useState2 = _sliced_to_array(useState(''), 2), activeLabel = _useState2[0], setActiveLabel = _useState2[1];
    var locale = useContext(I18nContext).locale;
    var _useBrowserContext = useBrowserContext(), prefixCls = _useBrowserContext.prefixCls, wrapSSR = _useBrowserContext.wrapSSR, hashId = _useBrowserContext.hashId;
    var _useMemo = useMemo(function() {
        if (!activeSuggestion) {
            return {
                items: [],
                loading: false
            };
        }
        var result = request(activeSuggestion);
        return {
            items: result.items || [],
            loading: result.loading || false
        };
    }, [
        activeSuggestion,
        request
    ]), results = _useMemo.items, loading = _useMemo.loading;
    var handleExecuteSearch = function handleExecuteSearch(suggestion) {
        setActiveSuggestion(suggestion);
        setActiveLabel(suggestion.label);
        setCurrentView('results');
    };
    var totalResultsTemplate = locale['browser.totalResults'] || 'Total ${count} results';
    return wrapSSR(/*#__PURE__*/ React.createElement("div", null, currentView === 'suggestions' && /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(List, {
        dataSource: suggestions,
        split: false,
        renderItem: function renderItem(item) {
            return /*#__PURE__*/ React.createElement(List.Item, {
                style: SUGGESTION_ITEM_STYLE,
                onClick: function onClick() {
                    return handleExecuteSearch(item);
                },
                className: classNames("".concat(prefixCls, "-suggestion"), hashId),
                actions: [
                    /*#__PURE__*/ React.createElement("div", {
                        key: "count"
                    }, /*#__PURE__*/ React.createElement(Tag, {
                        style: _object_spread_props(_object_spread({}, RESULT_COUNT_TAG_STYLE), {
                            marginRight: '-8px'
                        })
                    }, typeof countFormatter === 'function' ? countFormatter(item.count) : compileTemplate(totalResultsTemplate, {
                        count: String(item.count)
                    })))
                ]
            }, /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-suggestion-content"), hashId)
            }, /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-suggestion-icon"), hashId)
            }, suggestionIcon || /*#__PURE__*/ React.createElement(Search, null)), /*#__PURE__*/ React.createElement(Tooltip, {
                title: item.label,
                mouseEnterDelay: 0.5
            }, /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-suggestion-text"), hashId)
            }, item.label))));
        }
    })), currentView === 'results' && /*#__PURE__*/ React.createElement(BrowserList, {
        items: results,
        activeLabel: activeLabel,
        onBack: function onBack() {
            return setCurrentView('suggestions');
        },
        countFormatter: countFormatter,
        emptyText: emptyText,
        loading: loading,
        loadingText: loadingText,
        onLocate: onLocate
    })));
};
export default Browser;
