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 _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 { Anchor, ConfigProvider } from "antd";
import { nanoid } from "nanoid";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Node } from "slate";
import { useDebounce, useGetSetState } from "../../BaseMarkdownEditor";
import { useEditorStore } from "../store";
import { getOffsetTop, slugify } from "../utils/dom";
var TocTitle = function(param) {
    var children = param.children;
    return /*#__PURE__*/ React.createElement("span", {
        style: {
            maxWidth: 200,
            display: 'inline-block',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            fontSize: 14
        }
    }, children);
};
/**
 * 目录项缓存
 *
 * 使用 WeakMap 可以避免内存泄漏，当 schema 对象被垃圾回收时，
 * 对应的缓存也会自动清理
 */ var cache = new Map();
/**
 * 构建目录树
 *
 * 将扁平的标题列表转换为层次化的树结构，支持任意层级嵌套
 *
 * @param headers - 扁平的标题列表
 * @returns 构建好的目录树根节点
 */ function buildTree(headers) {
    // 创建虚拟根节点，用于统一处理顶级节点
    var root = {
        title: '',
        children: [],
        id: '',
        key: nanoid()
    };
    // 如果没有标题，直接返回空的根节点
    if (!headers.length) return root;
    // 使用栈来维护当前的层级路径
    var stack = [
        {
            node: root,
            level: 0
        }
    ];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = headers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var header = _step.value;
            var newNode = {
                title: header.title,
                children: [],
                id: header.id,
                key: nanoid(),
                level: header.level
            };
            // 关键逻辑：找到合适的父节点
            // 如果当前标题的层级小于等于栈顶节点的层级，需要弹出栈直到找到合适的父节点
            while(stack.length > 0 && stack[stack.length - 1].level >= header.level){
                stack.pop();
            }
            // 安全检查：如果栈为空，重置为根节点
            if (stack.length === 0) {
                stack.push({
                    node: root,
                    level: 0
                });
            }
            // 当前栈顶即为父节点
            var parent = stack[stack.length - 1].node;
            parent.children.push(newNode);
            // 将新节点压入栈，以便后续节点可能作为其子节点
            stack.push({
                node: newNode,
                level: header.level
            });
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return root;
}
/**
 * 将目录树转换为 Anchor 组件所需的数据格式
 *
 * 递归地将 TreeNode 结构转换为 AnchorItem 结构，
 * 只支持最多3层嵌套以保证良好的用户体验
 *
 * @param node - 目录树节点
 * @returns Anchor 组件的数据项数组
 */ function convertToAnchorItems(node) {
    var _node_children;
    // 如果节点没有子节点，返回空数组
    if (!((_node_children = node.children) === null || _node_children === void 0 ? void 0 : _node_children.length)) return [];
    return node.children.map(function(child) {
        var _child_children;
        return {
            id: child.id,
            key: child.key,
            href: "#".concat(slugify(child.id)),
            title: /*#__PURE__*/ React.createElement(TocTitle, {
                key: "title-".concat(child.id)
            }, child.title),
            // 支持二级子标题
            children: (_child_children = child.children) === null || _child_children === void 0 ? void 0 : _child_children.map(function(subChild) {
                var _subChild_children;
                return {
                    id: subChild.id,
                    key: subChild.key,
                    href: "#".concat(slugify(subChild.id)),
                    title: /*#__PURE__*/ React.createElement(TocTitle, {
                        key: "title-".concat(subChild.id)
                    }, subChild.title),
                    // 支持三级子标题（最大深度）
                    children: (_subChild_children = subChild.children) === null || _subChild_children === void 0 ? void 0 : _subChild_children.map(function(subSubChild) {
                        return {
                            id: subSubChild.id,
                            key: subSubChild.key,
                            href: "#".concat(slugify(subSubChild.id)),
                            title: /*#__PURE__*/ React.createElement(TocTitle, {
                                key: "title-".concat(subSubChild.id)
                            }, subSubChild.title)
                        };
                    })
                };
            }),
            level: child.level
        };
    });
}
/**
 * 目录容器组件
 * 用于处理目录的边界和溢出情况
 */ var TocContainer = function(param) {
    var children = param.children, containerRef = param.containerRef;
    var _useState = _sliced_to_array(useState(null), 2), containerRect = _useState[0], setContainerRect = _useState[1];
    useEffect(function() {
        var updateRect = function() {
            if (containerRef.current) {
                setContainerRect(containerRef.current.getBoundingClientRect());
            }
        };
        updateRect();
        window.addEventListener('resize', updateRect);
        window.addEventListener('scroll', updateRect);
        return function() {
            window.removeEventListener('resize', updateRect);
            window.removeEventListener('scroll', updateRect);
        };
    }, [
        containerRef
    ]);
    // 检查容器是否在视口内且有足够的空间
    var shouldRenderInContainer = useMemo(function() {
        if (!containerRect) return false;
        var isInViewport = containerRect.top < window.innerHeight && containerRect.bottom > 0;
        var hasEnoughSpace = containerRect.height > 200; // 最小高度要求
        return isInViewport && hasEnoughSpace;
    }, [
        containerRect
    ]);
    return /*#__PURE__*/ React.createElement(ConfigProvider, {
        getPopupContainer: function() {
            if (shouldRenderInContainer && containerRef.current) {
                return containerRef.current;
            }
            return document.body;
        },
        getTargetContainer: function() {
            return containerRef.current || document.body;
        }
    }, children);
};
/**
 * 目录组件
 *
 * 基于编辑器内容自动生成目录，支持：
 * - 自动提取1-4级标题
 * - 智能滚动定位和高亮
 * - 内部滚动和页面滚动的双重支持
 * - 性能优化的缓存机制
 *
 * @param schema - 编辑器的内容数据
 * @param anchorProps - 传递给 Anchor 组件的额外属性
 * @returns 目录组件
 */ export var TocHeading = function(param) {
    var schema = param.schema, anchorProps = param.anchorProps, _param_useCustomContainer = param.useCustomContainer, useCustomContainer = _param_useCustomContainer === void 0 ? true : _param_useCustomContainer;
    var markdownContainerRef = useEditorStore().markdownContainerRef;
    // 使用 useGetSetState 管理组件状态
    var _useGetSetState = _sliced_to_array(useGetSetState({
        headings: [],
        active: ''
    }), 2), state = _useGetSetState[0], setState = _useGetSetState[1];
    // 用于标识是否正在进行内部滚动的标志
    var isScrollingInternally = useRef(false);
    /**
   * 从 schema 中提取标题信息
   *
   * 遍历 schema 数组，提取所有的标题元素（type 为 'head' 且 level 小于等于 4）
   * 使用缓存机制避免重复处理相同的 schema 对象
   */ var getHeading = useCallback(function() {
        // 如果没有 schema 数据，清空标题列表
        if (!(schema === null || schema === void 0 ? void 0 : schema.length)) {
            setState({
                headings: []
            });
            return;
        }
        var headings = [];
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            // 遍历 schema 提取标题
            for(var _iterator = schema[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var s = _step.value;
                // 只处理标题类型且层级不超过4的元素
                if (s.type === 'head' && s.level <= 4) {
                    var title = Node.string(s);
                    var id = slugify(title);
                    // 跳过空标题
                    if (!title) continue;
                    // 检查缓存
                    var cached = cache.get(s);
                    if (cached) {
                        headings.push(cached);
                        continue;
                    }
                    // 创建新的标题对象
                    var heading = {
                        title: title,
                        level: s.level,
                        id: id,
                        key: nanoid(),
                        schema: s
                    };
                    // 缓存标题对象
                    cache.set(s, heading);
                    headings.push(heading);
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        setState({
            headings: headings
        });
    }, [
        schema,
        setState
    ]);
    // 当 schema 发生变化时重新提取标题
    useEffect(function() {
        cache.clear(); // 清理缓存，避免内存泄漏
        getHeading();
    }, [
        schema,
        getHeading
    ]);
    // 使用防抖优化频繁的 schema 变化
    useDebounce(getHeading, 100, [
        schema
    ]);
    /**
   * 处理内部容器滚动
   *
   * 当编辑器内部发生滚动时，更新当前激活的标题
   */ useEffect(function() {
        var container = markdownContainerRef.current;
        if (!container) return;
        var handleScroll = function(e) {
            // 只在内部滚动时处理
            if (!isScrollingInternally.current) return;
            var target = e.target;
            var scrollTop = target.scrollTop;
            var currentHeadings = state().headings.slice().reverse();
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                // 从下往上查找第一个滚动位置超过的标题
                for(var _iterator = currentHeadings[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var heading = _step.value;
                    var element = document.getElementById(heading.id);
                    if (element && scrollTop > getOffsetTop(element, container) - 20) {
                        setState({
                            active: heading.id
                        });
                        return;
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
            // 如果没有找到合适的标题，清空激活状态
            setState({
                active: ''
            });
        };
        container.addEventListener('scroll', handleScroll, {
            passive: true
        });
        return function() {
            container.removeEventListener('scroll', handleScroll);
        };
    }, [
        markdownContainerRef,
        setState,
        state
    ]);
    /**
   * 处理页面滚动
   *
   * 当页面发生滚动时，更新当前激活的标题
   * 只在非内部滚动时处理，避免冲突
   */ useEffect(function() {
        var handleScroll = function() {
            // 服务端渲染检查
            if (typeof window === 'undefined') return;
            // 如果正在进行内部滚动，忽略页面滚动
            if (isScrollingInternally.current) return;
            var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            var currentHeadings = state().headings.slice().reverse();
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                // 从下往上查找第一个滚动位置超过的标题
                for(var _iterator = currentHeadings[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var heading = _step.value;
                    var element = document.getElementById(heading.id);
                    if (element) {
                        var elementTop = element.getBoundingClientRect().top + scrollTop;
                        if (scrollTop >= elementTop - 100) {
                            setState({
                                active: heading.id
                            });
                            return;
                        }
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
            // 如果没有找到合适的标题，清空激活状态
            setState({
                active: ''
            });
        };
        window.addEventListener('scroll', handleScroll, {
            passive: true
        });
        return function() {
            window.removeEventListener('scroll', handleScroll);
        };
    }, [
        setState,
        state
    ]);
    /**
   * 处理锚点点击事件
   *
   * 根据目标元素的位置选择合适的滚动方式：
   * - 如果目标在编辑器容器内，使用内部滚动
   * - 否则使用页面滚动
   */ var handleAnchorClick = useCallback(function(e, link) {
        e.preventDefault();
        // 从链接中提取目标 ID
        var targetId = link.href.split('#')[1];
        var targetElement = document.getElementById(targetId);
        if (!targetElement) {
            console.warn('Target element with id "'.concat(targetId, '" not found'));
            return;
        }
        var container = markdownContainerRef.current;
        if (container && container.contains(targetElement)) {
            // 目标元素在容器内部，使用内部滚动
            isScrollingInternally.current = true;
            var offsetTop = getOffsetTop(targetElement, container);
            container.scrollTo({
                top: offsetTop - 20,
                behavior: 'smooth'
            });
            // 滚动完成后重置标志
            setTimeout(function() {
                isScrollingInternally.current = false;
            }, 500);
        } else {
            // 目标元素在容器外部，使用页面滚动
            isScrollingInternally.current = false;
            targetElement.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
            // 补偿固定导航栏的高度
            setTimeout(function() {
                window.scrollBy(0, -100);
            }, 100);
        }
    }, [
        markdownContainerRef
    ]);
    // 使用 useMemo 优化性能，避免不必要的重新计算
    var treeData = useMemo(function() {
        return buildTree(state().headings);
    }, [
        state().headings
    ]);
    var items = useMemo(function() {
        return convertToAnchorItems(treeData);
    }, [
        treeData
    ]);
    // 如果没有目录项，不渲染组件
    if (!items.length) {
        return null;
    }
    // 如果禁用了自定义容器，直接渲染 Anchor
    if (!useCustomContainer) {
        return /*#__PURE__*/ React.createElement(Anchor, _object_spread_props(_object_spread({
            style: {
                minWidth: 200,
                maxHeight: 'min(calc(100vh - 180px), 70vh)',
                overflowY: 'auto',
                overflowX: 'hidden',
                paddingRight: 4
            },
            offsetTop: 96,
            onClick: handleAnchorClick
        }, anchorProps), {
            items: items
        }));
    }
    // 使用自定义容器渲染
    return /*#__PURE__*/ React.createElement(TocContainer, {
        containerRef: markdownContainerRef
    }, /*#__PURE__*/ React.createElement(Anchor, _object_spread_props(_object_spread({
        style: {
            minWidth: 200,
            maxHeight: 'min(calc(100vh - 180px), 70vh)',
            overflowY: 'auto',
            overflowX: 'hidden',
            paddingRight: 4
        },
        offsetTop: 96,
        onClick: handleAnchorClick
    }, anchorProps), {
        items: items
    })));
};
