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 _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 _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 _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 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 = {}, 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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
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 "clsx";
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 { useRefFunction } from "../Hooks/useRefFunction";
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 { JinjaTemplatePanel } from "./editor/tools/JinjaTemplatePanel";
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 I18nBoundary from "./I18nBoundary";
import { PluginContext } from "./plugin";
import { useStyle } from "./style";
import { exportHtml } from "./utils/exportHtml";
import { sanitizeEditorChromeStyle } from "./utils/sanitizeChromeStyle";
// 组合器函数
var composeEditors = function composeEditors(editor, plugins) {
    if (plugins.length > 1) {
        return plugins.reduce(function(acc, plugin) {
            return plugin.withEditor ? plugin.withEditor(acc) : acc;
        }, editor);
    }
    return editor;
};
/** Slate 编辑路径：可编辑、或只读但 renderMode=slate（Slate 文档） */ var BaseMarkdownEditorSlate = function BaseMarkdownEditorSlate(props) {
    var _ref, _props_streaming, _props_readonly;
    var _props_jinja, _effectiveJinja_templatePanel, _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, rawStyle = props.style, tmp = props.contentStyle, rawContentStyle = tmp === void 0 ? {
        height: '100%'
    } : tmp, editorStyle = props.editorStyle, height = props.height, children = props.children, _renderMode = props.renderMode, _renderType = props.renderType, rest = _object_without_properties(props, [
        "initValue",
        "width",
        "toolBar",
        "editorRef",
        "toc",
        "readonly",
        "lazy",
        "style",
        "contentStyle",
        "editorStyle",
        "height",
        "children",
        "renderMode",
        "renderType"
    ]);
    var contentStyle = sanitizeEditorChromeStyle(rawContentStyle);
    var rootStyle = sanitizeEditorChromeStyle(rawStyle);
    var _useState = _sliced_to_array(useState(false), 2), editorMountStatus = _useState[0], setMountedStatus = _useState[1];
    var isEditorFocusedRef = useRef(false);
    var setEditorFocused = useRefFunction(function(focused) {
        isEditorFocusedRef.current = focused;
    });
    var keyTask$ = useMemo(function() {
        return new Subject();
    }, []);
    var markdownEditorRef = useRef(composeEditors(withMarkdown(withReact(withHistory(createEditor()))), props.plugins || []));
    var markdownContainerRef = useRef(null);
    var pluginsForInitParseRef = useRef(props.plugins);
    pluginsForInitParseRef.current = props.plugins;
    useEffect(function() {
        withErrorReporting(markdownEditorRef.current);
    }, []);
    useEffect(function() {
        if (!(rest === null || rest === void 0 ? void 0 : rest.onBlur)) return;
        if (readonly) return;
        var handleClickOutside = function handleClickOutside(event) {
            if (isEditorFocusedRef.current && 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);
                setEditorFocused(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return function() {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [
        readonly,
        rest === null || rest === void 0 ? void 0 : rest.onBlur,
        props.plugins,
        setEditorFocused
    ]);
    useEffect(function() {
        var _markdownContainerRef_current;
        var handleEditorFocus = function handleEditorFocus() {
            var _markdownContainerRef_current;
            if (((_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : _markdownContainerRef_current.contains(document.activeElement)) || markdownContainerRef.current === document.activeElement) {
                setEditorFocused(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
    ]);
    var initSchemaValue = useMemo(function() {
        var parseResult = parserMdToSchema(initValue || '', pluginsForInitParseRef.current || []);
        var list = (parseResult === null || parseResult === void 0 ? void 0 : parseResult.schema) || [];
        if (!props.readonly && list.length === 0) {
            list = _to_consumable_array(list).concat([
                EditorUtils.p
            ]);
        }
        var schema = props.initSchemaValue || (initValue ? list : JSON.parse(JSON.stringify([
            EditorUtils.p
        ])));
        var filtered = (schema === null || schema === void 0 ? void 0 : schema.filter(function(item) {
            if (item.type === 'paragraph' && item.children.length === 0) {
                return false;
            }
            if ((item.type === 'list' || item.type === 'bulleted-list' || item.type === 'numbered-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;
        })) || [];
        return EditorUtils.coalesceRootAllEmptyParagraphs(filtered);
    }, [
        initValue,
        props.readonly,
        props.initSchemaValue
    ]);
    var instance = useMemo(function() {
        return {
            store: store,
            markdownContainerRef: markdownContainerRef,
            markdownEditorRef: markdownEditorRef,
            exportHtml: function exportHtml1(filename) {
                var htmlContent = store.getHtmlContent();
                exportHtml(htmlContent, filename);
            }
        };
    }, []);
    useSystemKeyboard(keyTask$, instance.store, props, markdownContainerRef);
    useImperativeHandle(editorRef, function() {
        return {
            store: instance.store,
            markdownContainerRef: markdownContainerRef,
            markdownEditorRef: markdownEditorRef,
            exportHtml: instance.exportHtml
        };
    }, [
        instance,
        editorMountStatus
    ]);
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls("agentic-md-editor");
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _useState1 = _sliced_to_array(useState([]), 2), showCommentList = _useState1[0], setShowComment = _useState1[1];
    var _useState2 = _sliced_to_array(useState(initSchemaValue), 2), schema = _useState2[0], setSchema = _useState2[1];
    useEffect(function() {
        setSchema(initSchemaValue);
    }, [
        initSchemaValue
    ]);
    var _useState3 = _sliced_to_array(useState(false), 2), openInsertCompletion = _useState3[0], setOpenInsertCompletion = _useState3[1];
    var _useState4 = _sliced_to_array(useState(false), 2), refreshFloatBar = _useState4[0], setRefreshFloatBar = _useState4[1];
    var insertCompletionText$ = useMemo(function() {
        return new Subject();
    }, []);
    var openInsertLink$ = useMemo(function() {
        return new Subject();
    }, []);
    var _useState5 = _sliced_to_array(useState(null), 2), domRect = _useState5[0], setDomRect = _useState5[1];
    var jinjaEnabled = ((_props_jinja = props.jinja) === null || _props_jinja === void 0 ? void 0 : _props_jinja.enable) === true || Array.isArray(props.plugins) && props.plugins.some(function(p) {
        return p.jinja === true;
    });
    var pluginWithJinja = Array.isArray(props.plugins) ? props.plugins.find(function(p) {
        return p.jinja === true;
    }) : undefined;
    var effectiveJinja = props.jinja ? props.jinja : (pluginWithJinja === null || pluginWithJinja === void 0 ? void 0 : pluginWithJinja.jinjaConfig) ? pluginWithJinja.jinjaConfig : pluginWithJinja ? {
        enable: true
    } : undefined;
    var jinjaTemplatePanelEnabled = jinjaEnabled && effectiveJinja !== undefined && effectiveJinja !== null && effectiveJinja.templatePanel !== false && (_type_of(effectiveJinja.templatePanel) !== 'object' || ((_effectiveJinja_templatePanel = effectiveJinja.templatePanel) === null || _effectiveJinja_templatePanel === void 0 ? void 0 : _effectiveJinja_templatePanel.enable) !== false);
    var _useState6 = _sliced_to_array(useState(false), 2), openJinjaTemplate = _useState6[0], setOpenJinjaTemplate = _useState6[1];
    var _useState7 = _sliced_to_array(useState(null), 2), jinjaAnchorPath = _useState7[0], setJinjaAnchorPath = _useState7[1];
    var isStreaming = (_ref = (_props_streaming = props.streaming) !== null && _props_streaming !== void 0 ? _props_streaming : props.typewriter) !== null && _ref !== void 0 ? _ref : false;
    var _obj;
    return wrapSSR(/*#__PURE__*/ React.createElement(I18nBoundary, 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: isStreaming,
            readonly: (_props_readonly = props.readonly) !== null && _props_readonly !== void 0 ? _props_readonly : false,
            editorProps: effectiveJinja !== undefined ? _object_spread_props(_object_spread({}, props), {
                jinja: effectiveJinja
            }) : props || {},
            markdownEditorRef: markdownEditorRef,
            markdownContainerRef: markdownContainerRef,
            openJinjaTemplate: openJinjaTemplate,
            setOpenJinjaTemplate: setOpenJinjaTemplate,
            jinjaAnchorPath: jinjaAnchorPath,
            setJinjaAnchorPath: setJinjaAnchorPath,
            jinjaEnabled: jinjaEnabled,
            jinjaTemplatePanelEnabled: jinjaTemplatePanelEnabled
        }
    }, /*#__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)),
        "data-testid": "markdown-editor",
        style: _object_spread({
            width: width || '100%',
            height: height || 'auto'
        }, rootStyle)
    }, !readonly && (toolBar === null || toolBar === void 0 ? void 0 : toolBar.enable) === true ? /*#__PURE__*/ React.createElement("div", {
        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", {
        className: classNames("".concat(baseClassName, "-container"), props.containerClassName, hashId),
        style: _object_spread({
            height: !readonly && (toolBar === null || toolBar === void 0 ? void 0 : toolBar.enable) ? "calc(100% - 56px)" : '100%'
        }, (contentStyle === null || contentStyle === void 0 ? void 0 : contentStyle.padding) !== undefined ? {
            '--agentic-ui-content-padding': "".concat(typeof contentStyle.padding === 'number' ? "".concat(contentStyle.padding, "px") : contentStyle.padding),
            padding: contentStyle.padding
        } : {}, contentStyle),
        ref: function ref(dom) {
            markdownContainerRef.current = dom;
            setMountedStatus(true);
        },
        tabIndex: -1
    }, /*#__PURE__*/ React.createElement(SlateMarkdownEditor, _object_spread_props(_object_spread({
        prefixCls: baseClassName
    }, rest), {
        lazy: lazy,
        onChange: function onChange(value, s) {
            var _rest_onChange;
            setSchema(s);
            rest === null || rest === void 0 ? void 0 : (_rest_onChange = rest.onChange) === null || _rest_onChange === void 0 ? void 0 : _rest_onChange.call(rest, value, s);
        },
        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"))
    }), 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) || {}), jinjaTemplatePanelEnabled ? /*#__PURE__*/ React.createElement(JinjaTemplatePanel, null) : null), children)))));
};
export default BaseMarkdownEditorSlate;
