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 _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);
}
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 { runFunction } from "@ant-design/pro-components";
import { ChevronDown } from "@sofa-design/icons";
import { ConfigProvider, Dropdown } from "antd";
import classNames from "classnames";
import React, { useContext, useEffect, useRef, useState } from "react";
import { ReactEditor, useSlate } from "slate-react";
import { SuggestionConnext } from "../../../../MarkdownInputField/Suggestion";
import { useStyle } from "./style";
/**
 * TagPopup 组件 - 在编辑器中显示一个标签弹出选择框
 *
 * 该组件在编辑器中创建一个交互式标签选择弹出框，允许用户从预定义列表中选择标签。
 * 当选择一个标签时，会调用提供的回调函数并关闭弹出框。该组件与 Slate 编辑器集成，
 * 可以感知当前的节点路径。
 *
 * @param props - 组件属性
 * @param props.items - 可选的下拉菜单项列表
 * @param props.onSelect - 当选择一个项时的回调函数，接收所选项的键和路径
 * @param props.children - 触发器元素内容
 * @param props.dropdownRender - 自定义下拉菜单渲染函数
 * @param props.dropdownStyle - 下拉菜单的样式
 * @param props.menu - 自定义菜单配置
 * @param props.notFoundContent - 未找到内容时显示的内容
 * @param props.className - 组件的额外 CSS 类名
 * @param props.open - 控制下拉菜单是否打开
 * @param props.onOpenChange - 下拉菜单打开状态变化时的回调
 * @param props.text - 包含文本内容
 *
 * @returns 一个带有下拉菜单的标签弹出组件
 */ var getNodePath = function(editor, domRef) {
    if (!domRef.current) return null;
    try {
        var slateNode = ReactEditor.toSlateNode(editor, domRef.current);
        return ReactEditor.findPath(editor, slateNode);
    } catch (error) {
        // 如果无法从 DOM 节点解析 Slate 节点，返回 null
        // 这在测试环境或某些边缘情况下可能会发生
        return null;
    }
};
var updateNodeContext = function(editor, domRef, suggestionConnext, props, onSelect, pathRef) {
    var path = getNodePath(editor, domRef);
    if (!path) return;
    pathRef.current = path;
    if (suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.triggerNodeContext) {
        suggestionConnext.triggerNodeContext.current = _object_spread_props(_object_spread({}, props), {
            text: props.text
        });
    }
    if (suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.onSelectRef) {
        suggestionConnext.onSelectRef.current = function(newValue) {
            var _suggestionConnext_setOpen;
            var currentPath = getNodePath(editor, domRef);
            onSelect === null || onSelect === void 0 ? void 0 : onSelect(newValue, currentPath || path || []);
            suggestionConnext === null || suggestionConnext === void 0 ? void 0 : (_suggestionConnext_setOpen = suggestionConnext.setOpen) === null || _suggestionConnext_setOpen === void 0 ? void 0 : _suggestionConnext_setOpen.call(suggestionConnext, false);
        };
    }
};
var loadItemsData = function(items, props, setLoading, setSelectedItems) {
    return _async_to_generator(function() {
        var result;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (typeof items !== 'function') return [
                        2
                    ];
                    setLoading(true);
                    return [
                        4,
                        items(props)
                    ];
                case 1:
                    result = _state.sent();
                    if (Array.isArray(result)) {
                        setSelectedItems(result || []);
                    }
                    setLoading(false);
                    return [
                        2
                    ];
            }
        });
    })();
};
var initializeAutoOpen = function(autoOpen, type, setOpen, suggestionConnext) {
    var _suggestionConnext_setOpen;
    if (!autoOpen) return;
    if (type === 'dropdown') {
        setOpen(true);
        return;
    }
    suggestionConnext === null || suggestionConnext === void 0 ? void 0 : (_suggestionConnext_setOpen = suggestionConnext.setOpen) === null || _suggestionConnext_setOpen === void 0 ? void 0 : _suggestionConnext_setOpen.call(suggestionConnext, true);
};
var handleMouseEnter = function(domRef) {
    var target = domRef.current;
    if (!target) return;
    target.removeAttribute('data-no-focus');
};
var handleMouseLeave = function(domRef) {
    var target = domRef.current;
    if (!target) return;
    target.setAttribute('data-no-focus', '');
};
var createDefaultDom = function(domRef, baseCls, hashId, loading, selectedItems, children, text, placeholder, isOpen) {
    var isEmpty = !(text === null || text === void 0 ? void 0 : text.trim());
    var hasItems = (selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.length) > 0;
    var _obj;
    return /*#__PURE__*/ React.createElement("div", {
        ref: domRef,
        "data-tag-popup-input": true,
        "data-no-focus": true,
        className: classNames("".concat(baseCls, "-input"), hashId, (_obj = {
            empty: isEmpty
        }, _define_property(_obj, "".concat(baseCls, "-loading"), loading), _define_property(_obj, "".concat(baseCls, "-has-arrow"), hasItems), _obj)),
        onMouseEnter: function() {
            return handleMouseEnter(domRef);
        },
        onMouseLeave: function() {
            return handleMouseLeave(domRef);
        },
        title: placeholder,
        contentEditable: !hasItems ? undefined : false
    }, children, hasItems && /*#__PURE__*/ React.createElement(ChevronDown, {
        className: classNames("".concat(baseCls, "-arrow"), hashId, {
            empty: isEmpty,
            open: isOpen
        })
    }));
};
var getRenderDom = function(tagRender, props, defaultDom, onSelect, currentNodePath) {
    if (!tagRender) return defaultDom;
    return tagRender(_object_spread_props(_object_spread({}, props), {
        text: props.text,
        onSelect: function(value, tagNode) {
            onSelect === null || onSelect === void 0 ? void 0 : onSelect((value === null || value === void 0 ? void 0 : value.trim()) || '', currentNodePath.current || [], tagNode);
        }
    }), defaultDom);
};
var handlePanelClick = function(suggestionConnext, props, onSelect, currentNodePath) {
    var _suggestionConnext_setOpen;
    if (suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.triggerNodeContext) {
        suggestionConnext.triggerNodeContext.current = _object_spread_props(_object_spread({}, props), {
            text: props.text
        });
    }
    if (suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.onSelectRef) {
        suggestionConnext.onSelectRef.current = function(newValue) {
            var _suggestionConnext_setOpen;
            onSelect === null || onSelect === void 0 ? void 0 : onSelect((newValue === null || newValue === void 0 ? void 0 : newValue.trim()) || '', currentNodePath.current || []);
            suggestionConnext === null || suggestionConnext === void 0 ? void 0 : (_suggestionConnext_setOpen = suggestionConnext.setOpen) === null || _suggestionConnext_setOpen === void 0 ? void 0 : _suggestionConnext_setOpen.call(suggestionConnext, false);
        };
    }
    suggestionConnext === null || suggestionConnext === void 0 ? void 0 : (_suggestionConnext_setOpen = suggestionConnext.setOpen) === null || _suggestionConnext_setOpen === void 0 ? void 0 : _suggestionConnext_setOpen.call(suggestionConnext, true);
};
var canOpen = function(props, placeholder) {
    if (!props.beforeOpenChange) return true;
    return props.beforeOpenChange(true, _object_spread_props(_object_spread({}, props), {
        text: props.text,
        placeholder: placeholder
    }));
};
var handleClick = function(e, props, placeholder, type, suggestionConnext, onSelect, currentNodePath) {
    e.preventDefault();
    e.stopPropagation();
    if (!canOpen(props, placeholder)) return;
    if (type === 'dropdown') return;
    handlePanelClick(suggestionConnext, props, onSelect, currentNodePath);
};
export var TagPopup = function(props) {
    var _ref = props || {}, onSelect = _ref.onSelect, items = _ref.items, children = _ref.children, type = _ref.type;
    var editor = useSlate();
    var _useState = _sliced_to_array(useState(false), 2), open = _useState[0], setOpen = _useState[1];
    var _React_useState = _sliced_to_array(React.useState(false), 2), loading = _React_useState[0], setLoading = _React_useState[1];
    var domRef = useRef(null);
    var suggestionConnext = useContext(SuggestionConnext);
    var antdContext = useContext(ConfigProvider.ConfigContext);
    var baseCls = antdContext === null || antdContext === void 0 ? void 0 : antdContext.getPrefixCls('agentic-tag-popup');
    var _useStyle = useStyle(baseCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var currentNodePath = useRef();
    useEffect(function() {
        var path = getNodePath(editor, domRef);
        if (path) {
            currentNodePath.current = path;
        }
    }, [
        editor.children,
        props.text
    ]);
    useEffect(function() {
        updateNodeContext(editor, domRef, suggestionConnext, props, onSelect, currentNodePath);
    }, [
        props.text
    ]);
    var _useState1 = _sliced_to_array(useState(function() {
        return typeof items === 'function' ? [] : items || [];
    }), 2), selectedItems = _useState1[0], setSelectedItems = _useState1[1];
    useEffect(function() {
        loadItemsData(items, props, setLoading, setSelectedItems);
    }, [
        open,
        items
    ]);
    useEffect(function() {
        var _props_onChange;
        (_props_onChange = props.onChange) === null || _props_onChange === void 0 ? void 0 : _props_onChange.call(props, props.text || '', _object_spread_props(_object_spread({}, props), {
            text: props.text,
            onSelect: function(value) {
                onSelect === null || onSelect === void 0 ? void 0 : onSelect((value === null || value === void 0 ? void 0 : value.trim()) || '', currentNodePath.current || []);
            }
        }));
    }, [
        props.text,
        suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.open
    ]);
    useEffect(function() {
        initializeAutoOpen(props.autoOpen, type, setOpen, suggestionConnext);
    }, []);
    var placeholder = props.placeholder;
    var isOpen = type === 'dropdown' ? open : (suggestionConnext === null || suggestionConnext === void 0 ? void 0 : suggestionConnext.open) || false;
    var defaultDom = createDefaultDom(domRef, baseCls, hashId, loading, selectedItems, children, props.text, placeholder, isOpen);
    var renderDom = getRenderDom(props.tagRender, props, defaultDom, onSelect, currentNodePath);
    // 预先计算容器 className 与 style，减少 JSX 中的嵌套
    var containerClassName = classNames(baseCls, hashId, props.className, props.prefixCls, props.tagTextClassName, "".concat(baseCls, "-type-").concat(type));
    var containerStyle = _object_spread({}, runFunction(props.tagTextStyle, _object_spread_props(_object_spread({}, props), {
        text: props.text,
        placeholder: placeholder
    })));
    var handleContainerClick = function(e) {
        return handleClick(e, props, placeholder, type, suggestionConnext, onSelect, currentNodePath);
    };
    var isDropdown = type === 'dropdown';
    var dropdownMenu = {
        items: selectedItems,
        onClick: function(e) {
            var _e_key, _suggestionConnext_setOpen;
            onSelect === null || onSelect === void 0 ? void 0 : onSelect(((_e_key = e.key) === null || _e_key === void 0 ? void 0 : _e_key.trim()) || '', currentNodePath.current || []);
            suggestionConnext === null || suggestionConnext === void 0 ? void 0 : (_suggestionConnext_setOpen = suggestionConnext.setOpen) === null || _suggestionConnext_setOpen === void 0 ? void 0 : _suggestionConnext_setOpen.call(suggestionConnext, false);
        }
    };
    var content = isDropdown ? /*#__PURE__*/ React.createElement(Dropdown, {
        trigger: [
            'click'
        ],
        open: open,
        onOpenChange: setOpen,
        menu: dropdownMenu
    }, renderDom) : renderDom;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: containerClassName,
        style: containerStyle,
        onClick: handleContainerClick
    }, content));
};
