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 { ConfigProvider, Empty, Segmented, Spin } from "antd";
import classNames from "clsx";
import DOMPurify from "dompurify";
import React, { useContext, useMemo, useState } from "react";
import { I18nContext } from "../../I18n";
import { MarkdownEditor } from "../../MarkdownEditor";
import { useHtmlPreviewStyle } from "./style";
/**
 * HtmlPreview 组件 - HTML预览组件
 *
 * 该组件提供HTML内容的预览和代码查看功能，支持预览模式和代码模式的切换。
 * 使用DOMPurify进行安全的内容清理，支持iframe预览和Markdown代码显示。
 *
 * @component
 * @description HTML预览组件，支持预览和代码模式切换
 * @param {HtmlPreviewProps} props - 组件属性
 * @param {string} props.html - HTML内容字符串
 * @param {'generating' | 'loading' | 'done' | 'error'} [props.status] - 内容状态
 * @param {HtmlViewMode} [props.viewMode] - 当前视图模式（受控模式）
 * @param {HtmlViewMode} [props.defaultViewMode='preview'] - 默认视图模式
 * @param {(mode: HtmlViewMode) => void} [props.onViewModeChange] - 视图模式变化回调
 * @param {Partial<MarkdownEditorProps>} [props.markdownEditorProps] - Markdown编辑器配置
 * @param {React.IframeHTMLAttributes<HTMLIFrameElement>} [props.iframeProps] - iframe属性
 * @param {Object} [props.labels] - 自定义标签文本
 * @param {React.ReactNode | (() => React.ReactNode)} [props.loadingRender] - 自定义加载渲染
 * @param {React.ReactNode | (() => React.ReactNode)} [props.errorRender] - 自定义错误渲染
 * @param {string} [props.className] - 自定义CSS类名
 * @param {React.CSSProperties} [props.style] - 自定义样式
 * @param {boolean} [props.showSegmented=true] - 是否显示分段控制器
 * @param {Array<{label: React.ReactNode, value: string}>} [props.segmentedItems] - 自定义分段选项
 *
 * @example
 * ```tsx
 * <HtmlPreview
 *   html="<h1>Hello World</h1>"
 *   status="done"
 *   defaultViewMode="preview"
 *   onViewModeChange={(mode) => console.log('模式切换:', mode)}
 *   labels={{ preview: '预览', code: '源码' }}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的HTML预览组件
 *
 * @remarks
 * - 支持预览模式和代码模式切换
 * - 使用DOMPurify进行安全的内容清理
 * - 提供iframe预览功能
 * - 支持Markdown代码显示
 * - 提供加载和错误状态处理
 * - 支持自定义渲染内容
 * - 响应式布局设计
 * - 支持受控和非受控模式
 */ export var HtmlPreview = function HtmlPreview(props) {
    var html = props.html, inputStatus = props.status, viewMode = props.viewMode, _props_defaultViewMode = props.defaultViewMode, defaultViewMode = _props_defaultViewMode === void 0 ? 'preview' : _props_defaultViewMode, onViewModeChange = props.onViewModeChange, markdownEditorProps = props.markdownEditorProps, iframeProps = props.iframeProps, labels = props.labels, loadingRender = props.loadingRender, errorRender = props.errorRender, className = props.className, style = props.style, _props_showSegmented = props.showSegmented, showSegmented = _props_showSegmented === void 0 ? true : _props_showSegmented, segmentedItems = props.segmentedItems, emptyRender = props.emptyRender;
    var status = inputStatus === 'generating' ? 'loading' : inputStatus;
    var isControlled = viewMode !== undefined;
    var _useState = _sliced_to_array(useState(defaultViewMode), 2), innerMode = _useState[0], setInnerMode = _useState[1];
    var mode = isControlled ? viewMode : innerMode;
    var locale = useContext(I18nContext).locale;
    var handleModeChange = function handleModeChange(m) {
        if (!isControlled) setInnerMode(m);
        onViewModeChange === null || onViewModeChange === void 0 ? void 0 : onViewModeChange(m);
    };
    // 始终在 html 变化时更新 iframe 内容，避免首次未显示
    var iframeHtml = useMemo(function() {
        return DOMPurify.sanitize(html || '');
    }, [
        html
    ]);
    var labelsMap = {
        preview: (labels === null || labels === void 0 ? void 0 : labels.preview) || (locale === null || locale === void 0 ? void 0 : locale['htmlPreview.preview']) || '预览',
        code: (labels === null || labels === void 0 ? void 0 : labels.code) || (locale === null || locale === void 0 ? void 0 : locale['htmlPreview.code']) || '代码'
    };
    // 使用 ConfigProvider 获取前缀类名
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('workspace-html-preview');
    var overlayNode = function() {
        if (status !== 'loading' && status !== 'error') return null;
        var loadingNode = typeof loadingRender === 'function' ? loadingRender() : loadingRender;
        var errorNode = typeof errorRender === 'function' ? errorRender() : errorRender;
        var _obj;
        return /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-overlay"), (_obj = {}, _define_property(_obj, "".concat(prefixCls, "-overlay--loading"), status === 'loading'), _define_property(_obj, "".concat(prefixCls, "-overlay--error"), status === 'error'), _obj))
        }, status === 'loading' ? loadingNode || /*#__PURE__*/ React.createElement(Spin, null) : errorNode || /*#__PURE__*/ React.createElement("span", null, (locale === null || locale === void 0 ? void 0 : locale['htmlPreview.renderFailed']) || '页面渲染失败'));
    }();
    var getMergedMdConfig = function getMergedMdConfig() {
        var defaultMdConfig = {
            width: '100%',
            height: '100%',
            contentStyle: {
                width: '100%',
                padding: 0,
                marginTop: -10
            },
            codeProps: {
                showGutter: true,
                showLineNumbers: true,
                hideToolBar: true
            }
        };
        return _object_spread({}, defaultMdConfig, markdownEditorProps);
    };
    var _useHtmlPreviewStyle = useHtmlPreviewStyle(prefixCls), wrapSSR = _useHtmlPreviewStyle.wrapSSR, hashId = _useHtmlPreviewStyle.hashId;
    var isEmpty = (html !== null && html !== void 0 ? html : '').trim() === '';
    var shouldShowEmpty = isEmpty && status !== 'loading' && status !== 'error';
    var emptyNode = typeof emptyRender === 'function' ? emptyRender() : emptyRender;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames(prefixCls, className, hashId),
        style: style
    }, showSegmented && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-actions"), hashId)
    }, segmentedItems && segmentedItems.length > 0 ? /*#__PURE__*/ React.createElement(Segmented, {
        options: segmentedItems,
        value: mode,
        onChange: function onChange(v) {
            return handleModeChange(String(v));
        }
    }) : /*#__PURE__*/ React.createElement(Segmented, {
        size: "small",
        options: [
            {
                label: labelsMap.preview,
                value: 'preview'
            },
            {
                label: labelsMap.code,
                value: 'code'
            }
        ],
        value: mode,
        onChange: function onChange(v) {
            return handleModeChange(v);
        }
    })), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-content"), hashId),
        style: {
            minHeight: 240
        }
    }, overlayNode, shouldShowEmpty ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-empty"), hashId)
    }, emptyNode || /*#__PURE__*/ React.createElement(Empty, {
        description: (locale === null || locale === void 0 ? void 0 : locale['workspace.empty']) || 'No data'
    })) : mode === 'code' ? /*#__PURE__*/ React.createElement(MarkdownEditor, _object_spread_props(_object_spread({}, getMergedMdConfig()), {
        readonly: true,
        toc: false,
        initValue: "```html\n".concat(html || '', "\n```")
    })) : /*#__PURE__*/ React.createElement("iframe", _object_spread({
        title: "html-preview",
        className: classNames("".concat(prefixCls, "-iframe"), hashId),
        sandbox: (iframeProps === null || iframeProps === void 0 ? void 0 : iframeProps.sandbox) || 'allow-scripts',
        srcDoc: iframeHtml,
        key: iframeHtml
    }, iframeProps)))));
};
export default HtmlPreview;
