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 _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = _object_without_properties_loose(source, excluded);
    var key, i;
    if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceSymbolKeys.length; i++){
            key = sourceSymbolKeys[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 = {};
    var sourceKeys = Object.keys(source);
    var key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) 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);
}
import { ConfigProvider } from "antd";
import classNames from "classnames";
import React, { useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Subject } from "rxjs";
import { createEditor } from "slate";
import { withHistory } from "slate-history";
import { withReact } from "slate-react";
import { I18nProvide } from "../I18n";
import { CommentList } from "./editor/components/CommentList";
import { SlateMarkdownEditor } from "./editor/Editor";
import { parserMdToSchema } from "./editor/parser/parserMdToSchema";
import { parserSlateNodeToMarkdown } from "./editor/parser/parserSlateNodeToMarkdown";
import { withMarkdown } from "./editor/plugins";
import { withErrorReporting } from "./editor/plugins/catchError";
import { EditorStore, EditorStoreContext } from "./editor/store";
import { InsertAutocomplete } from "./editor/tools/InsertAutocomplete";
import { InsertLink } from "./editor/tools/InsertLink";
import { TocHeading } from "./editor/tools/Leading";
import { FloatBar } from "./editor/tools/ToolBar/FloatBar";
import ToolBar from "./editor/tools/ToolBar/ToolBar";
import { EditorUtils } from "./editor/utils/editorUtils";
import { useSystemKeyboard } from "./editor/utils/keyboard";
import { PluginContext } from "./plugin";
import { useStyle } from "./style";
import { exportHtml } from "./utils/exportHtml";
// 原生表格功能已集成到编辑器中
export { EditorUtils, parserMdToSchema };
export * from "./editor/elements";
export * from "./editor/utils";
export * from "./el";
export * from "./types";
// 组合器函数
var composeEditors = function(editor, plugins) {
    if (plugins.length > 1) {
        return plugins.reduce(function(acc, plugin) {
            return plugin.withEditor ? plugin.withEditor(acc) : acc;
        }, editor);
    }
    return editor;
};
/**
 * BaseMarkdownEditor 组件 - 基础Markdown编辑器组件
 *
 * 该组件是Markdown编辑器的核心实现，基于Slate.js构建，提供完整的Markdown编辑功能。
 * 支持插件系统、工具栏、目录、只读模式等功能，是MarkdownEditor的基础组件。
 *
 * @component
 * @description 基础Markdown编辑器组件，提供核心的Markdown编辑功能
 * @param {MarkdownEditorProps} props - 组件属性
 * @param {string} [props.initValue] - 初始值
 * @param {(value: string) => void} [props.onChange] - 内容变化回调
 * @param {React.RefObject} [props.editorRef] - 编辑器引用
 * @param {boolean} [props.readonly] - 是否只读模式
 * @param {Plugin[]} [props.plugins] - 插件列表
 * @param {ToolBarConfig} [props.toolBar] - 工具栏配置
 * @param {boolean} [props.toc] - 是否显示目录
 * @param {string|number} [props.width] - 编辑器宽度
 * @param {string|number} [props.height] - 编辑器高度
 * @param {React.CSSProperties} [props.style] - 容器样式
 * @param {React.CSSProperties} [props.contentStyle] - 内容区域样式
 * @param {React.CSSProperties} [props.editorStyle] - 编辑器样式
 * @param {MarkdownRenderConfig} [props.markdownRenderConfig] - Markdown渲染配置
 * @param {Function} [props.onBlur] - 失焦回调
 * @param {Function} [props.onFocus] - 聚焦回调
 *
 * @example
 * ```tsx
 * <BaseMarkdownEditor
 *   initValue="# Hello World"
 *   onChange={(value) => console.log('内容变化:', value)}
 *   editorRef={editorRef}
 *   readonly={false}
 *   toc={true}
 *   toolBar={{ show: true }}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的基础Markdown编辑器组件
 *
 * @remarks
 * - 基于Slate.js构建
 * - 支持插件系统扩展
 * - 提供完整的工具栏功能
 * - 支持目录生成
 * - 支持只读模式
 * - 提供焦点管理
 * - 支持错误捕获
 * - 支持键盘事件处理
 * - 提供Markdown解析和渲染
 */ export var BaseMarkdownEditor = function(props) {
    var _props_floatBar, _props_floatBar1, _props_textAreaProps;
    var initValue = props.initValue, width = props.width, _props_toolBar = props.toolBar, toolBar = _props_toolBar === void 0 ? {} : _props_toolBar, editorRef = props.editorRef, _props_toc = props.toc, toc = _props_toc === void 0 ? false : _props_toc, readonly = props.readonly, lazy = props.lazy, style = props.style, _props_contentStyle = props.contentStyle, contentStyle = _props_contentStyle === void 0 ? {
        height: '100%'
    } : _props_contentStyle, editorStyle = props.editorStyle, height = props.height, rest = _object_without_properties(props, [
        "initValue",
        "width",
        "toolBar",
        "editorRef",
        "toc",
        "readonly",
        "lazy",
        "style",
        "contentStyle",
        "editorStyle",
        "height"
    ]);
    // 是否挂载
    var _useState = _sliced_to_array(useState(false), 2), editorMountStatus = _useState[0], setMountedStatus = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), isEditorFocused = _useState1[0], setIsEditorFocused = _useState1[1];
    // 键盘事件
    var keyTask$ = useMemo(function() {
        return new Subject();
    }, []);
    // markdown 编辑器实例
    var markdownEditorRef = useRef(composeEditors(withMarkdown(withReact(withHistory(createEditor()))), props.plugins || []));
    var markdownContainerRef = useRef(null);
    // 错误捕获
    useEffect(function() {
        withErrorReporting(markdownEditorRef.current);
    }, []);
    // 处理点击外部区域
    useEffect(function() {
        if (!(rest === null || rest === void 0 ? void 0 : rest.onBlur)) return;
        if (readonly) return;
        var handleClickOutside = function(event) {
            if (isEditorFocused && markdownContainerRef.current && !markdownContainerRef.current.contains(event.target)) {
                var _markdownEditorRef_current, _markdownEditorRef_current1, _rest_onBlur;
                EditorUtils.blur(markdownEditorRef.current);
                rest === null || rest === void 0 ? void 0 : (_rest_onBlur = rest.onBlur) === null || _rest_onBlur === void 0 ? void 0 : _rest_onBlur.call(rest, parserSlateNodeToMarkdown(((_markdownEditorRef_current = markdownEditorRef.current) === null || _markdownEditorRef_current === void 0 ? void 0 : _markdownEditorRef_current.children) || [], '', [], props.plugins), (_markdownEditorRef_current1 = markdownEditorRef.current) === null || _markdownEditorRef_current1 === void 0 ? void 0 : _markdownEditorRef_current1.children, event);
                setIsEditorFocused(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return function() {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [
        readonly,
        rest === null || rest === void 0 ? void 0 : rest.onBlur,
        props.plugins,
        isEditorFocused
    ]);
    // 监听编辑器焦点
    useEffect(function() {
        var _markdownContainerRef_current;
        var handleEditorFocus = function() {
            var _markdownContainerRef_current;
            if (((_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.contains(document.activeElement)) || markdownContainerRef.current === document.activeElement) {
                setIsEditorFocused(true);
            }
        };
        (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.addEventListener('focusin', handleEditorFocus);
        return function() {
            var _markdownContainerRef_current;
            (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.removeEventListener('focusin', handleEditorFocus);
        };
    }, []);
    var store = useMemo(function() {
        return new EditorStore(markdownEditorRef, props.plugins, props.markdownToHtmlOptions);
    }, [
        props.plugins,
        props.markdownToHtmlOptions
    ]);
    /**
   * 初始化 schema
   */ var initSchemaValue = useMemo(function() {
        var _parserMdToSchema;
        var list = (_parserMdToSchema = parserMdToSchema(initValue, props.plugins)) === null || _parserMdToSchema === void 0 ? void 0 : _parserMdToSchema.schema;
        if (!props.readonly) {
            list.push(EditorUtils.p);
        }
        var schema = props.initSchemaValue || (initValue ? list : JSON.parse(JSON.stringify([
            EditorUtils.p
        ])));
        return schema === null || schema === void 0 ? void 0 : schema.filter(function(item) {
            if (item.type === 'p' && item.children.length === 0) {
                return false;
            }
            if (item.type === 'list' && item.children.length === 0) {
                return false;
            }
            if (item.type === 'listItem' && item.children.length === 0) {
                return false;
            }
            if (item.type === 'heading' && item.children.length === 0) {
                return false;
            }
            return true;
        });
    }, []);
    // 初始化实例
    var instance = useMemo(function() {
        return {
            store: store,
            markdownContainerRef: markdownContainerRef,
            markdownEditorRef: markdownEditorRef,
            exportHtml: function(filename) {
                var htmlContent = store.getHtmlContent();
                exportHtml(htmlContent, filename);
            }
        };
    }, []);
    // 初始化键盘事件
    useSystemKeyboard(keyTask$, instance.store, props, markdownContainerRef);
    // 导入外部 hooks
    useImperativeHandle(editorRef, function() {
        return {
            store: instance.store,
            markdownContainerRef: markdownContainerRef,
            markdownEditorRef: markdownEditorRef,
            exportHtml: instance.exportHtml
        };
    }, [
        instance,
        editorMountStatus
    ]);
    var context = useContext(ConfigProvider.ConfigContext);
    // ---- css style ----
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls("agentic-md-editor");
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    // --- css style end ---
    // 评论列表
    var _useState2 = _sliced_to_array(useState([]), 2), showCommentList = _useState2[0], setShowComment = _useState2[1];
    // schema 数据
    var _useState3 = _sliced_to_array(useState(initSchemaValue), 2), schema = _useState3[0], setSchema = _useState3[1];
    var _useState4 = _sliced_to_array(useState(false), 2), openInsertCompletion = _useState4[0], setOpenInsertCompletion = _useState4[1];
    var _useState5 = _sliced_to_array(useState(false), 2), refreshFloatBar = _useState5[0], setRefreshFloatBar = _useState5[1];
    var insertCompletionText$ = useMemo(function() {
        return new Subject();
    }, []);
    var openInsertLink$ = useMemo(function() {
        return new Subject();
    }, []);
    var _useState6 = _sliced_to_array(useState(null), 2), domRect = _useState6[0], setDomRect = _useState6[1];
    var _props_typewriter, _props_readonly;
    var _obj;
    return wrapSSR(/*#__PURE__*/ React.createElement(I18nProvide, null, /*#__PURE__*/ React.createElement(PluginContext.Provider, {
        value: props.plugins || []
    }, /*#__PURE__*/ React.createElement(EditorStoreContext.Provider, {
        value: {
            keyTask$: keyTask$,
            insertCompletionText$: insertCompletionText$,
            openInsertLink$: openInsertLink$,
            openInsertCompletion: openInsertCompletion,
            setOpenInsertCompletion: setOpenInsertCompletion,
            setRefreshFloatBar: setRefreshFloatBar,
            refreshFloatBar: refreshFloatBar,
            rootContainer: props.rootContainer,
            setShowComment: setShowComment,
            store: instance.store,
            domRect: domRect,
            setDomRect: setDomRect,
            typewriter: (_props_typewriter = props.typewriter) !== null && _props_typewriter !== void 0 ? _props_typewriter : false,
            readonly: (_props_readonly = props.readonly) !== null && _props_readonly !== void 0 ? _props_readonly : false,
            editorProps: props || {},
            markdownEditorRef: markdownEditorRef,
            markdownContainerRef: markdownContainerRef
        }
    }, /*#__PURE__*/ React.createElement("div", {
        id: props.id ? String(props.id) || undefined : undefined,
        className: classNames(baseClassName, 'markdown-editor', hashId, props.className, (_obj = {}, _define_property(_obj, "".concat(baseClassName, "-readonly"), readonly), _define_property(_obj, "".concat(baseClassName, "-edit"), !readonly), _define_property(_obj, "".concat(baseClassName, "-report"), props.reportMode), _define_property(_obj, "".concat(baseClassName, "-slide"), props.slideMode), _obj)),
        style: _object_spread({
            width: width || '100%',
            height: height || 'auto',
            display: 'flex',
            flexDirection: 'column',
            maxHeight: '100%',
            font: 'var(--font-text-paragraph-lg)',
            letterSpacing: 'var(--letter-spacing-paragraph-lg, normal)',
            color: 'var(--color-gray-text-default)'
        }, style)
    }, !readonly && (toolBar === null || toolBar === void 0 ? void 0 : toolBar.enable) === true ? /*#__PURE__*/ React.createElement("div", {
        style: {
            width: '100%',
            maxWidth: '100%',
            position: 'sticky',
            zIndex: 99,
            top: 0
        },
        className: classNames("".concat(baseClassName, "-toolbar-container"), _define_property({}, "".concat(baseClassName, "-min-toolbar"), toolBar.min))
    }, /*#__PURE__*/ React.createElement(ToolBar, {
        hideTools: toolBar.hideTools,
        extra: toolBar.extra,
        min: toolBar.min
    })) : readonly ? null : null, /*#__PURE__*/ React.createElement("div", {
        style: _object_spread({
            padding: '4px 20px',
            overflow: 'auto',
            display: 'flex',
            height: !readonly && (toolBar === null || toolBar === void 0 ? void 0 : toolBar.enable) ? "calc(100% - 56px)" : '100%',
            position: 'relative',
            gap: 24,
            outline: 'none'
        }, contentStyle),
        ref: function(dom) {
            markdownContainerRef.current = dom;
            setMountedStatus(true);
        },
        tabIndex: -1
    }, /*#__PURE__*/ React.createElement(SlateMarkdownEditor, _object_spread_props(_object_spread({
        prefixCls: baseClassName
    }, rest), {
        lazy: lazy,
        onChange: function(value, schema) {
            var _rest_onChange;
            setSchema(schema);
            rest === null || rest === void 0 ? void 0 : (_rest_onChange = rest.onChange) === null || _rest_onChange === void 0 ? void 0 : _rest_onChange.call(rest, value, schema);
        },
        initSchemaValue: initSchemaValue,
        style: editorStyle,
        instance: instance
    })), readonly ? props.reportMode ? ((_props_floatBar = props.floatBar) === null || _props_floatBar === void 0 ? void 0 : _props_floatBar.enable) === false ? null : /*#__PURE__*/ React.createElement(FloatBar, {
        readonly: true
    }) : null : ((_props_floatBar1 = props.floatBar) === null || _props_floatBar1 === void 0 ? void 0 : _props_floatBar1.enable) !== true ? null : /*#__PURE__*/ React.createElement(FloatBar, {
        readonly: false
    }), editorMountStatus && toc !== false && markdownContainerRef.current ? (showCommentList === null || showCommentList === void 0 ? void 0 : showCommentList.length) ? /*#__PURE__*/ React.createElement(CommentList, {
        commentList: showCommentList,
        comment: props.comment
    }) : /*#__PURE__*/ React.createElement(TocHeading, {
        schema: schema,
        anchorProps: props.anchorProps,
        useCustomContainer: true
    }) : (showCommentList === null || showCommentList === void 0 ? void 0 : showCommentList.length) ? /*#__PURE__*/ React.createElement(CommentList, {
        pure: true,
        commentList: showCommentList,
        comment: props.comment
    }) : null), readonly || (props === null || props === void 0 ? void 0 : (_props_textAreaProps = props.textAreaProps) === null || _props_textAreaProps === void 0 ? void 0 : _props_textAreaProps.enable) || (props === null || props === void 0 ? void 0 : props.reportMode) ? null : /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-focus")),
        style: {
            height: 64
        }
    }), readonly ? /*#__PURE__*/ React.createElement(React.Fragment, null) : /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(InsertLink, null), /*#__PURE__*/ React.createElement(InsertAutocomplete, (props === null || props === void 0 ? void 0 : props.insertAutocompleteProps) || {})))))));
};
