/**
 * @fileoverview Ace编辑器核心组件
 *
 * 负责Ace编辑器的初始化、配置和事件处理，包括：
 * - 编辑器生命周期管理
 * - 语法高亮配置
 * - 主题动态切换
 * - 键盘事件处理
 * - 内容变化监听
 * - 与 Slate 编辑器的集成
 *
 * @see {@link https://ace.c9.io/} Ace Editor 官方文档
 */ 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 _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = 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 isHotkey from "is-hotkey";
import { startTransition, useEffect, useRef, useState } from "react";
import { Editor, Path, Transforms } from "slate";
import { useRefFunction } from "../../../Hooks/useRefFunction";
import partialParse from "../../../MarkdownEditor/editor/parser/json-parse";
import { useEditorStore } from "../../../MarkdownEditor/editor/store";
import { getAceLangs, modeMap } from "../../../MarkdownEditor/editor/utils/ace";
import { EditorUtils } from "../../../MarkdownEditor/editor/utils/editorUtils";
import { loadAceEditor, loadAceTheme } from "../loadAceEditor";
/**
 * AceEditor 组件
 *
 * 封装 Ace Editor 的核心功能，提供代码编辑、语法高亮、主题切换等能力。
 *
 * @component
 * @param {AceEditorProps} props - 组件属性
 * @returns {Object} 返回包含 DOM 引用、编辑器引用、语言设置等方法的对象
 *
 * @example
 * ```tsx
 * const { dom, setLanguage, focusEditor } = AceEditor({
 *   element: codeNode,
 *   onUpdate: (data) => console.log('更新:', data),
 *   onShowBorderChange: (show) => setBorder(show),
 *   onHideChange: (hide) => setHide(hide),
 *   path: [0, 1],
 * });
 * ```
 *
 * @remarks
 * - 支持 100+ 种编程语言
 * - 支持多种主题切换
 * - 自动处理键盘事件和快捷键
 * - 与 Slate 编辑器深度集成
 */ export function AceEditor(_0) {
    var element = _0.element, onUpdate = _0.onUpdate, onShowBorderChange = _0.onShowBorderChange, onHideChange = _0.onHideChange, path = _0.path, _0_isSelected = _0.isSelected, isSelected = _0_isSelected === void 0 ? false : _0_isSelected, onSelectionChange = _0.onSelectionChange, props = _object_without_properties(_0, [
        "element",
        "onUpdate",
        "onShowBorderChange",
        "onHideChange",
        "path",
        "isSelected",
        "onSelectionChange"
    ]);
    var _editorProps_codeProps, _editorProps_codeProps1;
    var _useEditorStore = useEditorStore(), store = _useEditorStore.store, editorProps = _useEditorStore.editorProps, readonly = _useEditorStore.readonly;
    // 各种引用
    var codeRef = useRef(element.value || '');
    var pathRef = useRef(path);
    var posRef = useRef({
        row: 0,
        column: 0
    });
    var pasted = useRef(false);
    var debounceTimer = useRef(0);
    var editorRef = useRef();
    var dom = useRef(null);
    // Ace Editor 异步加载状态
    var _useState = _sliced_to_array(useState(false), 2), aceLoaded = _useState[0], setAceLoaded = _useState[1];
    var aceModuleRef = useRef(null);
    // 更新路径引用
    useEffect(function() {
        pathRef.current = path;
    }, [
        path
    ]);
    // 异步加载 Ace Editor 库
    useEffect(function() {
        if (process.env.NODE_ENV === 'test') {
            // 测试环境跳过加载
            setAceLoaded(true);
            return;
        }
        // 使用 startTransition 标记为非紧急更新
        startTransition(function() {
            // 异步加载在 startTransition 外部执行
            (function() {
                return _async_to_generator(function() {
                    var _editorProps_codeProps, aceModule, theme, error;
                    return _ts_generator(this, function(_state) {
                        switch(_state.label){
                            case 0:
                                _state.trys.push([
                                    0,
                                    3,
                                    ,
                                    4
                                ]);
                                return [
                                    4,
                                    loadAceEditor()
                                ];
                            case 1:
                                aceModule = _state.sent();
                                aceModuleRef.current = aceModule;
                                // 加载主题
                                theme = ((_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.theme) || props.theme || 'github';
                                return [
                                    4,
                                    loadAceTheme(theme)
                                ];
                            case 2:
                                _state.sent();
                                setAceLoaded(true);
                                return [
                                    3,
                                    4
                                ];
                            case 3:
                                error = _state.sent();
                                console.error('Failed to load Ace Editor:', error);
                                // 即使加载失败也设置 loaded，避免无限加载
                                setAceLoaded(true);
                                return [
                                    3,
                                    4
                                ];
                            case 4:
                                return [
                                    2
                                ];
                        }
                    });
                })();
            })();
        });
    }, [
        (_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.theme,
        props.theme
    ]);
    // 键盘事件处理
    var handleKeyDown = useRefFunction(function(e) {
        // 删除空代码块
        if (isHotkey('backspace', e)) {
            if (codeRef.current.trim() === '') {
                Editor.withoutNormalizing(store.editor, function() {
                    Transforms.delete(store.editor, {
                        at: pathRef.current
                    });
                    // 如果这是最后一个节点，使用替换而不是删除+插入，避免文档为空
                    Transforms.insertNodes(store.editor, {
                        type: 'paragraph',
                        children: [
                            {
                                text: ''
                            }
                        ]
                    }, {
                        at: pathRef.current,
                        select: true
                    });
                    Transforms.select(store.editor, Editor.start(store.editor, pathRef.current));
                });
                return;
            }
        }
        // Cmd/Ctrl + Enter: 插入新段落
        if (isHotkey('mod+enter', e) && pathRef.current) {
            EditorUtils.focus(store.editor);
            Transforms.insertNodes(store.editor, {
                type: 'paragraph',
                children: [
                    {
                        text: ''
                    }
                ]
            }, {
                at: Path.next(pathRef.current),
                select: true
            });
            e.stopPropagation();
            return;
        }
        // 转发键盘事件
        var newEvent = new KeyboardEvent(e.type, e);
        window.dispatchEvent(newEvent);
    });
    // 配置编辑器事件
    var setupEditorEvents = useRefFunction(function(codeEditor) {
        // 禁用默认查找快捷键
        codeEditor.commands.addCommand({
            name: 'disableFind',
            bindKey: {
                win: 'Ctrl-F',
                mac: 'Command-F'
            },
            exec: function exec() {}
        });
        var textarea = dom.current.querySelector('textarea');
        // 聚焦事件
        codeEditor.on('focus', function() {
            onShowBorderChange(false);
            onHideChange(false);
        });
        // 失焦事件
        codeEditor.on('blur', function() {
            codeEditor.selection.clearSelection();
        });
        // 光标变化事件
        codeEditor.selection.on('changeCursor', function() {
            setTimeout(function() {
                var pos = codeEditor.getCursorPosition();
                posRef.current = {
                    row: pos.row,
                    column: pos.column
                };
            });
        });
        // 粘贴事件
        codeEditor.on('paste', function(e) {
            if (pasted.current) {
                e.text = '';
            } else {
                pasted.current = true;
                setTimeout(function() {
                    pasted.current = false;
                }, 60);
            }
        });
        codeEditor.on('focus', function() {
            onSelectionChange === null || onSelectionChange === void 0 ? void 0 : onSelectionChange(true);
        });
        codeEditor.on('blur', function() {
            setTimeout(function() {
                onSelectionChange === null || onSelectionChange === void 0 ? void 0 : onSelectionChange(false);
            }, 160);
        });
        // 键盘事件
        textarea === null || textarea === void 0 ? void 0 : textarea.addEventListener('keydown', handleKeyDown);
        // 内容变化事件
        codeEditor.on('change', function() {
            if (readonly) return;
            clearTimeout(debounceTimer.current);
            debounceTimer.current = window.setTimeout(function() {
                if (typeof window === 'undefined') return;
                onUpdate({
                    value: codeEditor.getValue()
                });
                codeRef.current = codeEditor.getValue();
            }, 100);
        });
    });
    // 初始化 Ace 编辑器（仅在库加载完成后）
    // 注意： intentionally 不将 editorProps.codeProps 列入依赖，因其对象引用在父组件内容更新时会频繁变化，
    // 导致编辑器被不必要地销毁重建。codeProps 的配置在初始化时已应用，主题等动态变更由独立 effect 处理。
    useEffect(function() {
        if (process.env.NODE_ENV === 'test') return;
        if (!aceLoaded || !aceModuleRef.current || !dom.current) return;
        var codeProps = editorProps.codeProps || {};
        var value = element.value || '';
        if (element.language === 'json') {
            try {
                value = JSON.stringify(partialParse(value), null, 2);
            } catch (e) {}
        }
        // ace-builds 模块的默认导出就是 ace 对象
        // 使用类型断言确保类型正确
        var aceModule = aceModuleRef.current;
        var ace = aceModule.default || aceModule;
        var codeEditor = ace.edit(dom.current, _object_spread({
            useWorker: false,
            value: value,
            fontSize: 12,
            animatedScroll: true,
            maxLines: Infinity,
            wrap: true,
            tabSize: 4,
            readOnly: readonly,
            showPrintMargin: false,
            showLineNumbers: true,
            showGutter: true
        }, codeProps));
        editorRef.current = codeEditor;
        // 设置主题
        var theme = codeProps.theme || props.theme || 'github';
        codeEditor.setTheme("ace/theme/".concat(theme));
        // 设置语法高亮
        setTimeout(function() {
            return _async_to_generator(function() {
                var lang, aceLangs;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            lang = element.language;
                            if (modeMap.has(lang)) {
                                lang = modeMap.get(lang);
                            }
                            return [
                                4,
                                getAceLangs()
                            ];
                        case 1:
                            aceLangs = _state.sent();
                            if (aceLangs.has(lang)) {
                                codeEditor.session.setMode("ace/mode/".concat(lang));
                            }
                            return [
                                2
                            ];
                    }
                });
            })();
        }, 16);
        if (readonly) return;
        // 配置编辑器事件
        setupEditorEvents(codeEditor);
        return function() {
            clearTimeout(debounceTimer.current);
            codeEditor.destroy();
        };
    }, [
        aceLoaded,
        element.language,
        readonly,
        setupEditorEvents
    ]);
    // 监听外部值变化
    useEffect(function() {
        var value = element.value || '';
        if (element.language === 'json') {
            try {
                value = JSON.stringify(partialParse(value), null, 2);
            } catch (e) {}
        }
        if (value !== codeRef.current || readonly) {
            var _editorRef_current, _editorRef_current1;
            if (element) (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : _editorRef_current.setValue(value);
            (_editorRef_current1 = editorRef.current) === null || _editorRef_current1 === void 0 ? void 0 : _editorRef_current1.clearSelection();
        }
    }, [
        element.value
    ]);
    // 监听主题变化
    useEffect(function() {
        var _editorProps_codeProps;
        if (!editorRef.current || !aceLoaded) return;
        var theme = ((_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.theme) || props.theme || 'github';
        // 异步加载新主题
        startTransition(function() {
            (function() {
                return _async_to_generator(function() {
                    var _editorRef_current, error, // 尝试使用默认主题
                    _editorRef_current1;
                    return _ts_generator(this, function(_state) {
                        switch(_state.label){
                            case 0:
                                _state.trys.push([
                                    0,
                                    2,
                                    ,
                                    3
                                ]);
                                return [
                                    4,
                                    loadAceTheme(theme)
                                ];
                            case 1:
                                _state.sent();
                                (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : _editorRef_current.setTheme("ace/theme/".concat(theme));
                                return [
                                    3,
                                    3
                                ];
                            case 2:
                                error = _state.sent();
                                console.warn("Failed to load theme: ".concat(theme), error);
                                (_editorRef_current1 = editorRef.current) === null || _editorRef_current1 === void 0 ? void 0 : _editorRef_current1.setTheme("ace/theme/github");
                                return [
                                    3,
                                    3
                                ];
                            case 3:
                                return [
                                    2
                                ];
                        }
                    });
                })();
            })();
        });
    }, [
        (_editorProps_codeProps1 = editorProps.codeProps) === null || _editorProps_codeProps1 === void 0 ? void 0 : _editorProps_codeProps1.theme,
        props.theme,
        aceLoaded
    ]);
    // 暴露设置语言的方法
    var setLanguage = useRefFunction(function(changeLang) {
        return _async_to_generator(function() {
            var _element_language, lang, aceLangs, _editorRef_current, _editorRef_current1;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        lang = changeLang.toLowerCase();
                        if (((_element_language = element.language) === null || _element_language === void 0 ? void 0 : _element_language.toLowerCase()) === lang) return [
                            2
                        ];
                        onUpdate({
                            language: lang
                        });
                        if (modeMap.has(lang)) {
                            lang = modeMap.get(lang);
                        }
                        return [
                            4,
                            getAceLangs()
                        ];
                    case 1:
                        aceLangs = _state.sent();
                        if (aceLangs.has(lang)) {
                            ;
                            (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : _editorRef_current.session.setMode("ace/mode/".concat(lang));
                        } else {
                            ;
                            (_editorRef_current1 = editorRef.current) === null || _editorRef_current1 === void 0 ? void 0 : _editorRef_current1.session.setMode("ace/mode/text");
                        }
                        return [
                            2
                        ];
                }
            });
        })();
    });
    return {
        dom: dom,
        editorRef: editorRef,
        setLanguage: setLanguage,
        focusEditor: function focusEditor() {
            var _editorRef_current;
            return (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : _editorRef_current.focus();
        },
        isSelected: isSelected,
        onSelectionChange: onSelectionChange
    };
}
