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 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);
}
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 { Skeleton } from "antd";
import React, { useEffect, useLayoutEffect, useState } from "react";
import { useRefFunction } from "../../../../Hooks/useRefFunction";
import { MediaErrorLink } from "../../components/MediaErrorLink";
import { useGetSetState } from "../../utils";
import { getMediaType } from "../../utils/dom";
import { ReadonlyImage } from "./index";
/**
 * ReadonlyEditorImage 组件 - 只读图片预览组件
 *
 * 专门针对 readonly 模式优化的图片组件，移除了调整大小、选择等编辑相关功能。
 * 简化渲染逻辑，提升预览模式性能。
 *
 * @component
 * @description 只读图片预览组件，用于预览模式下的图片渲染
 * @param {ElementProps<MediaNode>} props - 组件属性
 * @param {MediaNode} props.element - 图片节点元素
 * @param {React.ReactNode} props.children - 子组件内容
 * @param {Object} props.attributes - 元素属性
 *
 * @example
 * ```tsx
 * <ReadonlyEditorImage
 *   element={imageNode}
 *   attributes={attributes}
 * >
 *   内容
 * </ReadonlyEditorImage>
 * ```
 *
 * @returns {React.ReactElement} 渲染的只读图片组件
 *
 * @remarks
 * - 移除调整大小功能
 * - 移除选择状态管理
 * - 保留加载状态和错误处理
 * - 使用 React.memo 优化性能
 * - 保持预览模式的视觉效果
 */ export var ReadonlyEditorImage = /*#__PURE__*/ React.memo(function(props) {
    var _state;
    var element = props.element, attributes = props.attributes, children = props.children;
    var htmlRef = React.useRef(null);
    var _useState = _sliced_to_array(useState(false), 2), showAsText = _useState[0], setShowAsText = _useState[1];
    var _useGetSetState = _sliced_to_array(useGetSetState({
        loadSuccess: true,
        url: '',
        type: getMediaType(element === null || element === void 0 ? void 0 : element.url, element.alt)
    }), 2), state = _useGetSetState[0], setState = _useGetSetState[1];
    // 如果 finished 为 false，设置 5 秒超时，超时后显示为文本
    useEffect(function() {
        if (element.finished === false) {
            setShowAsText(false);
            var timer = setTimeout(function() {
                setShowAsText(true);
            }, 5000);
            return function() {
                clearTimeout(timer);
            };
        } else {
            setShowAsText(false);
        }
    }, [
        element.finished
    ]);
    var initial = useRefFunction(function() {
        return _async_to_generator(function() {
            var type, realUrl, img;
            return _ts_generator(this, function(_state) {
                type = getMediaType(element === null || element === void 0 ? void 0 : element.url, element.alt);
                type = !type ? 'image' : type;
                setState({
                    type: [
                        'image',
                        'video',
                        'autio',
                        'attachment'
                    ].includes(type) ? type : 'other'
                });
                realUrl = element === null || element === void 0 ? void 0 : element.url;
                setState({
                    url: realUrl
                });
                if (state().type === 'image' || state().type === 'other') {
                    img = document.createElement('img');
                    img.referrerPolicy = 'no-referrer';
                    img.crossOrigin = 'anonymous';
                    img.src = realUrl;
                    img.onerror = function() {
                        setState({
                            loadSuccess: false
                        });
                    };
                    img.onload = function() {
                        setState({
                            loadSuccess: true
                        });
                    };
                }
                return [
                    2
                ];
            });
        })();
    });
    useLayoutEffect(function() {
        initial();
    }, [
        element === null || element === void 0 ? void 0 : element.url,
        initial
    ]);
    // 图片预览 DOM
    var imageDom = React.useMemo(function() {
        var _state;
        // 检查是否为不完整的图片（finished 状态）
        if (element.finished === false) {
            // 如果 5 秒后仍未完成，显示为文本
            if (showAsText) {
                return /*#__PURE__*/ React.createElement("div", {
                    style: {
                        padding: '8px 12px',
                        border: '1px solid #d9d9d9',
                        borderRadius: '4px',
                        color: 'rgba(0, 0, 0, 0.65)',
                        wordBreak: 'break-all'
                    }
                }, element.alt || element.url || '图片链接');
            }
            // 5 秒内显示 loading 状态的占位符
            return /*#__PURE__*/ React.createElement(Skeleton.Image, {
                active: true
            });
        }
        // 如果图片加载失败，显示为链接
        if (!state().loadSuccess) {
            var _state1, _state2;
            return /*#__PURE__*/ React.createElement(MediaErrorLink, {
                url: (_state1 = state()) === null || _state1 === void 0 ? void 0 : _state1.url,
                fallbackUrl: element === null || element === void 0 ? void 0 : element.url,
                displayText: (element === null || element === void 0 ? void 0 : element.alt) || ((_state2 = state()) === null || _state2 === void 0 ? void 0 : _state2.url) || (element === null || element === void 0 ? void 0 : element.url) || '图片链接',
                style: {
                    fontSize: '13px',
                    lineHeight: '1.5'
                }
            });
        }
        return /*#__PURE__*/ React.createElement(ReadonlyImage, {
            src: ((_state = state()) === null || _state === void 0 ? void 0 : _state.url) || (element === null || element === void 0 ? void 0 : element.url),
            alt: (element === null || element === void 0 ? void 0 : element.alt) || 'image',
            width: element.width,
            height: element.height,
            crossOrigin: "anonymous"
        });
    }, [
        state().type,
        (_state = state()) === null || _state === void 0 ? void 0 : _state.url,
        state().loadSuccess,
        element.finished,
        showAsText,
        element.url,
        element.alt,
        element.width,
        element.height
    ]);
    return /*#__PURE__*/ React.createElement("div", _object_spread_props(_object_spread({}, attributes), {
        "data-be": "image",
        "data-testid": "image-container",
        style: {
            position: 'relative',
            userSelect: 'none',
            WebkitUserSelect: 'none',
            MozUserSelect: 'none',
            msUserSelect: 'none',
            width: '100%',
            maxWidth: '100%',
            boxSizing: 'border-box'
        },
        draggable: false
    }), /*#__PURE__*/ React.createElement("div", {
        tabIndex: -1,
        style: {
            color: 'transparent',
            padding: 4,
            userSelect: 'none',
            display: 'flex',
            flexDirection: 'column',
            width: imageDom ? '100%' : undefined,
            maxWidth: '100%',
            boxSizing: 'border-box'
        },
        ref: htmlRef,
        draggable: false,
        contentEditable: false,
        "data-be": "image-container"
    }, imageDom, /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'none'
        }
    }, children)));
});
ReadonlyEditorImage.displayName = 'ReadonlyEditorImage';
