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_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread 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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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 { Plus } from "@sofa-design/icons";
import { Divider, Dropdown } from "antd";
import classNames from "clsx";
import React, { useContext, useMemo } from "react";
import { I18nContext } from "../../../../I18n";
import { useEditorStore } from "../../store";
import { getInsertOptions } from "../InsertAutocomplete";
import { useToolsConfig } from "./config/toolsConfig";
import { useToolBarLogic } from "./hooks/useToolBarLogic";
// Components
import { Node } from "slate";
import { ClearFormatButton } from "./components/ClearFormatButton";
import { ColorPickerButton } from "./components/ColorPickerButton";
import { FormatButton } from "./components/FormatButton";
import { FormattingTools } from "./components/FormattingTools";
import { HeadingDropdown } from "./components/HeadingDropdown";
import { LinkButton } from "./components/LinkButton";
import { ToolBarItem } from "./components/ToolBarItem";
import { UndoRedoButtons } from "./components/UndoRedoButtons";
// 节点类型常量
var TABLE_NODE_TYPES = [
    'table-cell',
    'table-row',
    'table',
    'thead',
    'tbody',
    'th',
    'td'
];
var LINK_ALLOWED_NODE_TYPES = [
    'head',
    'paragraph',
    'quote',
    'b-list',
    'n-list',
    't-list'
];
var HEADING_ALLOWED_NODE_TYPES = [
    'head',
    'paragraph'
];
// 工具函数
var isTableNode = function isTableNode(nodeType) {
    return TABLE_NODE_TYPES.includes(nodeType);
};
var isNodeInTable = function isNodeInTable(currentNode, markdownEditorRef) {
    var _currentNode_;
    if (!currentNode || !markdownEditorRef.current) {
        return false;
    }
    // 检查当前节点是否为表格类型
    if (isTableNode((_currentNode_ = currentNode[0]) === null || _currentNode_ === void 0 ? void 0 : _currentNode_.type)) {
        return true;
    }
    // 检查父节点是否为表格类型
    try {
        var parentNode = Node.parent(markdownEditorRef.current, currentNode[1]);
        return isTableNode(parentNode === null || parentNode === void 0 ? void 0 : parentNode.type);
    } catch (error) {
        // 如果获取父节点失败，假设不在表格内
        return false;
    }
};
/**
 * 基础工具栏
 */ export var BaseToolBar = /*#__PURE__*/ React.memo(function(props) {
    var baseClassName = props.prefix || "toolbar-action";
    var hashId = props.hashId;
    var _useEditorStore = useEditorStore(), markdownEditorRef = _useEditorStore.markdownEditorRef, keyTask$ = _useEditorStore.keyTask$, editorProps = _useEditorStore.editorProps, openInsertLink$ = _useEditorStore.openInsertLink$, domRect = _useEditorStore.domRect, store = _useEditorStore.store, setDomRect = _useEditorStore.setDomRect, refreshFloatBar = _useEditorStore.refreshFloatBar;
    var i18n = useContext(I18nContext);
    var toolsConfig = useToolsConfig();
    var toolBarLogic = useToolBarLogic({
        markdownEditorRef: markdownEditorRef,
        keyTask$: keyTask$,
        store: store,
        openInsertLink$: openInsertLink$,
        setDomRect: setDomRect,
        refreshFloatBar: refreshFloatBar,
        domRect: domRect
    });
    var currentNode = toolBarLogic.currentNode, highColor = toolBarLogic.highColor, isCodeNode = toolBarLogic.isCodeNode, isFormatActive = toolBarLogic.isFormatActive, isHighColorActive = toolBarLogic.isHighColorActive, isLinkActive = toolBarLogic.isLinkActive, handleUndo = toolBarLogic.handleUndo, handleRedo = toolBarLogic.handleRedo, handleClearFormat = toolBarLogic.handleClearFormat, handleFormat = toolBarLogic.handleFormat, handleHeadingChange = toolBarLogic.handleHeadingChange, handleColorChange = toolBarLogic.handleColorChange, handleToggleHighColor = toolBarLogic.handleToggleHighColor, handleToolClick = toolBarLogic.handleToolClick, handleInsertLink = toolBarLogic.handleInsertLink, handleInsert = toolBarLogic.handleInsert;
    // 插入选项
    var insertOptions = useMemo(function() {
        var filterOption = function filterOption(option) {
            // 过滤上传图片功能
            if (!(editorProps === null || editorProps === void 0 ? void 0 : editorProps.image) && option.task === 'uploadImage') {
                return false;
            }
            // 根据 showInsertAction 决定显示哪些选项
            return props.showInsertAction || option.task === 'list';
        };
        return getInsertOptions({
            isTop: false
        }, i18n.locale).map(function(o) {
            return o === null || o === void 0 ? void 0 : o.children;
        }).flat().filter(filterOption);
    }, [
        editorProps === null || editorProps === void 0 ? void 0 : editorProps.image,
        props.showInsertAction,
        i18n.locale
    ]);
    // 插入选项元素
    var insertOptionElements = useMemo(function() {
        return insertOptions.map(function(option) {
            return /*#__PURE__*/ React.createElement(ToolBarItem, {
                key: option.key,
                title: option.label.join(' '),
                icon: option.icon,
                onClick: function onClick() {
                    return handleInsert(option);
                },
                className: classNames("".concat(baseClassName, "-item"), hashId)
            });
        });
    }, [
        insertOptions,
        handleInsert,
        baseClassName,
        hashId
    ]);
    // 显示条件
    var showConditions = useMemo(function() {
        var _currentNode_, _currentNode_1;
        // 检查是否在表格内
        var isInTable = isNodeInTable(currentNode, markdownEditorRef);
        return {
            linkButton: currentNode && LINK_ALLOWED_NODE_TYPES.includes(currentNode === null || currentNode === void 0 ? void 0 : (_currentNode_ = currentNode[0]) === null || _currentNode_ === void 0 ? void 0 : _currentNode_.type) && !isInTable,
            headingDropdown: currentNode && HEADING_ALLOWED_NODE_TYPES.includes(currentNode === null || currentNode === void 0 ? void 0 : (_currentNode_1 = currentNode[0]) === null || _currentNode_1 === void 0 ? void 0 : _currentNode_1.type) && !isInTable,
            isInTable: isInTable
        };
    }, [
        currentNode
    ]);
    // 通用属性
    var commonProps = {
        baseClassName: baseClassName,
        hashId: hashId,
        i18n: i18n
    };
    // 工具栏元素生成器
    var createToolbarElement = function createToolbarElement(key, Component, props) {
        return /*#__PURE__*/ React.createElement(Component, _object_spread({
            key: key
        }, commonProps, props));
    };
    // 渲染常规工具栏
    var renderFullToolbar = useMemo(function() {
        var // 插入选项
        _elements;
        var elements = [];
        // 如果在表格内，只显示基本格式化工具
        if (showConditions.isInTable) {
            // 清除格式按钮
            elements.push(createToolbarElement('clear', ClearFormatButton, {
                onClear: handleClearFormat
            }));
            // 格式化按钮
            elements.push(createToolbarElement('format', FormatButton, {
                onFormat: handleFormat
            }));
            // 颜色选择器
            elements.push(createToolbarElement('color', ColorPickerButton, {
                highColor: highColor,
                isHighColorActive: isHighColorActive,
                onColorChange: handleColorChange,
                onToggleHighColor: handleToggleHighColor
            }));
            // 格式化工具（只显示加粗、斜体等基本格式）
            elements.push(createToolbarElement('formatting', FormattingTools, {
                tools: toolsConfig,
                editor: markdownEditorRef.current,
                isCodeNode: isCodeNode(),
                onToolClick: handleToolClick,
                isFormatActive: isFormatActive,
                isInTable: true,
                hideTools: props.hideTools
            }));
            return elements;
        }
        // 非表格内的完整工具栏
        // 撤销重做按钮
        if (props.showEditor) {
            elements.push(createToolbarElement('undo-redo', UndoRedoButtons, {
                onUndo: handleUndo,
                onRedo: handleRedo
            }));
        }
        // 清除格式按钮
        elements.push(createToolbarElement('clear', ClearFormatButton, {
            onClear: handleClearFormat
        }));
        // 格式化按钮
        elements.push(createToolbarElement('format', FormatButton, {
            onFormat: handleFormat
        }));
        // 标题下拉框
        if (showConditions.headingDropdown) {
            elements.push(createToolbarElement('heading', HeadingDropdown, {
                node: currentNode,
                hideTools: props.hideTools,
                onHeadingChange: handleHeadingChange
            }));
        }
        // 颜色选择器
        elements.push(createToolbarElement('color', ColorPickerButton, {
            highColor: highColor,
            isHighColorActive: isHighColorActive,
            onColorChange: handleColorChange,
            onToggleHighColor: handleToggleHighColor
        }));
        (_elements = elements).push.apply(_elements, _to_consumable_array(insertOptionElements));
        // 格式化工具
        elements.push(createToolbarElement('formatting', FormattingTools, {
            tools: toolsConfig,
            editor: markdownEditorRef.current,
            isCodeNode: isCodeNode(),
            onToolClick: handleToolClick,
            isFormatActive: isFormatActive,
            hideTools: props.hideTools
        }));
        // 链接按钮
        if (showConditions.linkButton) {
            elements.push(createToolbarElement('link', LinkButton, {
                onInsertLink: handleInsertLink,
                isLinkActive: isLinkActive
            }));
        }
        // 过滤隐藏的工具
        return props.hideTools ? elements.filter(function(element) {
            if (/*#__PURE__*/ React.isValidElement(element) && element.key) {
                var _props_hideTools;
                return !((_props_hideTools = props.hideTools) === null || _props_hideTools === void 0 ? void 0 : _props_hideTools.includes(element.key));
            }
            return true;
        }) : elements;
    }, [
        props.showEditor,
        props.hideTools,
        showConditions,
        currentNode,
        highColor,
        isHighColorActive,
        insertOptionElements,
        markdownEditorRef,
        isCodeNode,
        isFormatActive,
        isLinkActive,
        handleUndo,
        handleRedo,
        handleClearFormat,
        handleFormat,
        handleHeadingChange,
        handleColorChange,
        handleToggleHighColor,
        handleToolClick,
        handleInsertLink
    ]);
    // 渲染精简工具栏
    var renderMinToolbar = useMemo(function() {
        var _i18n_locale;
        if (!props.min) return null;
        // 如果在表格内，精简工具栏也要相应调整
        if (showConditions.isInTable) {
            return /*#__PURE__*/ React.createElement(React.Fragment, null, createToolbarElement('clear', ClearFormatButton, {
                onClear: handleClearFormat
            }), createToolbarElement('color', ColorPickerButton, {
                highColor: highColor,
                isHighColorActive: isHighColorActive,
                onColorChange: handleColorChange,
                onToggleHighColor: handleToggleHighColor
            }), createToolbarElement('formatting', FormattingTools, {
                tools: toolsConfig,
                editor: markdownEditorRef.current,
                isCodeNode: isCodeNode(),
                onToolClick: handleToolClick,
                isFormatActive: isFormatActive,
                isInTable: true,
                hideTools: props.hideTools
            }));
        }
        var dropdownItems = insertOptions.map(function(option) {
            var _option_label;
            return {
                label: /*#__PURE__*/ React.createElement("div", {
                    style: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: 8
                    }
                }, option.icon, (_option_label = option.label) === null || _option_label === void 0 ? void 0 : _option_label.at(0)),
                key: "min-".concat(option.key),
                onClick: function onClick() {
                    return handleInsert(option);
                }
            };
        });
        return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(ToolBarItem, {
            title: ((_i18n_locale = i18n.locale) === null || _i18n_locale === void 0 ? void 0 : _i18n_locale.moreActions) || '更多操作',
            icon: /*#__PURE__*/ React.createElement(Plus, null),
            className: classNames("".concat(baseClassName, "-item"), "".concat(baseClassName, "-item--more"), hashId),
            tabIndex: -1
        }, /*#__PURE__*/ React.createElement(Dropdown, {
            menu: {
                items: dropdownItems
            }
        }, /*#__PURE__*/ React.createElement(Plus, {
            role: "img",
            "aria-label": "Plus"
        }))), /*#__PURE__*/ React.createElement(Divider, {
            type: "vertical",
            style: {
                margin: '0 4px',
                height: '18px',
                borderColor: 'rgba(0,0,0,0.15)'
            }
        }), createToolbarElement('undo-redo', UndoRedoButtons, {
            onUndo: handleUndo,
            onRedo: handleRedo
        }), createToolbarElement('clear', ClearFormatButton, {
            onClear: handleClearFormat
        }), createToolbarElement('heading', HeadingDropdown, {
            node: currentNode,
            hideTools: props.hideTools,
            onHeadingChange: handleHeadingChange
        }), createToolbarElement('color', ColorPickerButton, {
            highColor: highColor,
            isHighColorActive: isHighColorActive,
            onColorChange: handleColorChange,
            onToggleHighColor: handleToggleHighColor
        }), createToolbarElement('formatting', FormattingTools, {
            tools: toolsConfig,
            editor: markdownEditorRef.current,
            isCodeNode: isCodeNode(),
            onToolClick: handleToolClick,
            isFormatActive: isFormatActive,
            hideTools: props.hideTools
        }));
    }, [
        props.min,
        insertOptions,
        handleInsert,
        baseClassName,
        hashId,
        currentNode,
        props.hideTools,
        highColor,
        isHighColorActive,
        markdownEditorRef,
        isCodeNode,
        isFormatActive,
        handleUndo,
        handleRedo,
        handleClearFormat,
        handleHeadingChange,
        handleColorChange,
        handleToggleHighColor,
        handleToolClick
    ]);
    // 渲染额外内容
    var renderExtra = useMemo(function() {
        if (!props.extra) return null;
        var extraStyle = {
            flex: 1,
            display: 'flex',
            justifyContent: 'flex-end',
            alignItems: 'center',
            height: '100%'
        };
        return /*#__PURE__*/ React.createElement("div", {
            style: extraStyle
        }, props.extra.map(function(item, index) {
            var key = "extra-".concat(index);
            if (/*#__PURE__*/ React.isValidElement(item)) {
                return item.type === 'span' ? /*#__PURE__*/ React.createElement("div", {
                    className: classNames("".concat(baseClassName, "-item"), hashId),
                    key: "".concat(key, "-span")
                }, item) : /*#__PURE__*/ React.cloneElement(item, {
                    key: key
                });
            }
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(baseClassName, "-item"), hashId),
                key: "".concat(key, "-div")
            }, item);
        }));
    }, [
        props.extra,
        baseClassName,
        hashId
    ]);
    return /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            height: '100%',
            gap: '1px',
            alignItems: 'center'
        }
    }, props.min ? renderMinToolbar : renderFullToolbar, renderExtra);
});
BaseToolBar.displayName = 'BaseToolBar';
