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 _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 _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 { useCallback, useEffect, useMemo, useState } from "react";
import { Editor, Element, Node, Text, Transforms } from "slate";
import { MarkdownFormatter } from "../../../../../Plugins/formatter";
import { getSelRect } from "../../../utils/dom";
import { EditorUtils } from "../../../utils/editorUtils";
export var useToolBarLogic = function useToolBarLogic(param) {
    var markdownEditorRef = param.markdownEditorRef, keyTask$ = param.keyTask$, store = param.store, openInsertLink$ = param.openInsertLink$, setDomRect = param.setDomRect, refreshFloatBar = param.refreshFloatBar, domRect = param.domRect;
    var _useState = _sliced_to_array(useState(false), 2), refresh = _useState[0], setRefresh = _useState[1];
    var _useState1 = _sliced_to_array(useState(null), 2), highColor = _useState1[0], setHighColor = _useState1[1];
    // 检查是否为代码节点
    var isCodeNode = useCallback(function(editor) {
        var _Editor_nodes = _sliced_to_array(Editor.nodes(editor, {
            match: function match(n) {
                return Element.isElement(n);
            },
            mode: 'lowest'
        }), 1), node = _Editor_nodes[0];
        return node && node[0].type === 'code';
    }, []);
    // 获取当前节点
    var currentNode = useMemo(function() {
        if (!markdownEditorRef.current) return null;
        var _Editor_nodes = _sliced_to_array(Editor.nodes(markdownEditorRef.current, {
            match: function match(n) {
                return Element.isElement(n);
            },
            mode: 'lowest'
        }), 1), node = _Editor_nodes[0];
        return node;
    }, [
        markdownEditorRef,
        refresh
    ]);
    // 检查格式是否激活
    var isFormatActive = useCallback(function(type) {
        if (!markdownEditorRef.current) return false;
        return EditorUtils.isFormatActive(markdownEditorRef.current, type);
    }, [
        markdownEditorRef,
        refresh
    ]);
    // 撤销操作
    var handleUndo = useCallback(function() {
        keyTask$.next({
            key: 'undo',
            args: []
        });
    }, [
        keyTask$
    ]);
    // 重做操作
    var handleRedo = useCallback(function() {
        keyTask$.next({
            key: 'redo',
            args: []
        });
    }, [
        keyTask$
    ]);
    // 清除格式
    var handleClearFormat = useCallback(function() {
        if (!markdownEditorRef.current || isCodeNode(markdownEditorRef.current)) return;
        EditorUtils.clearMarks(markdownEditorRef.current, true);
        EditorUtils.highColor(markdownEditorRef.current);
    }, [
        markdownEditorRef,
        isCodeNode
    ]);
    // 格式化文档
    var handleFormat = useCallback(function() {
        var editor = markdownEditorRef.current;
        if (!editor) return;
        var _Editor_nodes = _sliced_to_array(Editor.nodes(editor, {
            match: function match(n) {
                return Text.isText(n);
            },
            mode: 'all'
        }), 1), node = _Editor_nodes[0];
        if (node) {
            var content = Node.string(node.at(0));
            if (content.trim() === '') {
                var markdown = store.getMDContent();
                if (markdown) {
                    var formatted = MarkdownFormatter.format(markdown);
                    store.setMDContent(formatted);
                    setRefresh(function(r) {
                        return !r;
                    });
                }
                return;
            }
            var formatted1 = MarkdownFormatter.format(content);
            var selection = editor.selection;
            if (!selection) return;
            Transforms.insertText(editor, formatted1, {
                at: node[1]
            });
            Transforms.select(editor, node[1]);
        }
    }, [
        markdownEditorRef,
        store
    ]);
    // 标题变更
    var handleHeadingChange = useCallback(function(level) {
        keyTask$.next({
            key: 'head',
            args: [
                level
            ]
        });
    }, [
        keyTask$
    ]);
    // 颜色变更
    var handleColorChange = useCallback(function(color) {
        if (!markdownEditorRef.current || isCodeNode(markdownEditorRef.current)) return;
        EditorUtils.highColor(markdownEditorRef.current, color);
        setHighColor(color);
        setRefresh(function(r) {
            return !r;
        });
    }, [
        markdownEditorRef,
        isCodeNode
    ]);
    // 切换高亮颜色
    var handleToggleHighColor = useCallback(function() {
        if (!markdownEditorRef.current || isCodeNode(markdownEditorRef.current)) return;
        if (EditorUtils.isFormatActive(markdownEditorRef.current, 'highColor')) {
            EditorUtils.highColor(markdownEditorRef.current);
        } else {
            EditorUtils.highColor(markdownEditorRef.current, highColor || '#10b981');
        }
        setRefresh(function(r) {
            return !r;
        });
    }, [
        markdownEditorRef,
        isCodeNode,
        highColor
    ]);
    // 工具点击处理
    var handleToolClick = useCallback(function(tool) {
        if (!markdownEditorRef.current || isCodeNode(markdownEditorRef.current)) return;
        if (tool.onClick) {
            tool.onClick(markdownEditorRef.current);
        } else {
            EditorUtils.toggleFormat(markdownEditorRef.current, tool.type);
        }
        setRefresh(function(r) {
            return !r;
        });
    }, [
        markdownEditorRef,
        isCodeNode
    ]);
    // 插入链接
    var handleInsertLink = useCallback(function() {
        var _markdownEditorRef_current;
        var sel = (_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : _markdownEditorRef_current.selection;
        if (!sel) return;
        setDomRect(getSelRect());
        if (typeof window === 'undefined' || typeof window.matchMedia === 'undefined') return;
        openInsertLink$.next(sel);
    }, [
        markdownEditorRef,
        setDomRect,
        openInsertLink$
    ]);
    // 插入操作
    var handleInsert = useCallback(function(op) {
        if (!op) return;
        keyTask$.next({
            key: op.task,
            args: op.args
        });
    }, [
        keyTask$
    ]);
    // 监听变化
    useEffect(function() {
        setRefresh(function(r) {
            return !r;
        });
    }, [
        refreshFloatBar,
        domRect
    ]);
    return {
        currentNode: currentNode,
        highColor: highColor,
        isCodeNode: useCallback(function() {
            return markdownEditorRef.current ? isCodeNode(markdownEditorRef.current) : false;
        }, [
            isCodeNode,
            markdownEditorRef
        ]),
        isFormatActive: isFormatActive,
        isHighColorActive: isFormatActive('highColor'),
        isLinkActive: isFormatActive('url'),
        handleUndo: handleUndo,
        handleRedo: handleRedo,
        handleClearFormat: handleClearFormat,
        handleFormat: handleFormat,
        handleHeadingChange: handleHeadingChange,
        handleColorChange: handleColorChange,
        handleToggleHighColor: handleToggleHighColor,
        handleToolClick: handleToolClick,
        handleInsertLink: handleInsertLink,
        handleInsert: handleInsert
    };
};
