/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var debounce = require('lodash/debounce');
var amisCore = require('amis-core');
var Modal = require('./Modal.js');
var icons = require('./icons.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var debounce__default = /*#__PURE__*/_interopDefaultLegacy(debounce);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
exports.ImageActionKey = void 0;
(function (ImageActionKey) {
    /** 右旋转 */
    ImageActionKey["ROTATE_RIGHT"] = "rotateRight";
    /** 左旋转 */
    ImageActionKey["ROTATE_LEFT"] = "rotateLeft";
    /** 等比例放大 */
    ImageActionKey["ZOOM_IN"] = "zoomIn";
    /** 等比例缩小 */
    ImageActionKey["ZOOM_OUT"] = "zoomOut";
    /** 恢复原图缩放比例尺 */
    ImageActionKey["SCALE_ORIGIN"] = "scaleOrigin";
})(exports.ImageActionKey || (exports.ImageActionKey = {}));
var ImageGallery = /** @class */ (function (_super) {
    tslib.__extends(ImageGallery, _super);
    function ImageGallery() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isOpened: false,
            index: -1,
            items: [],
            tx: 0,
            ty: 0,
            scale: 1,
            rotate: 0,
            showToolbar: false,
            imageGallaryClassName: '',
            actions: ImageGallery.defaultProps.actions
        };
        _this.startX = 0;
        _this.startY = 0;
        _this.startTx = 0;
        _this.startTy = 0;
        _this.handleToolbarAction = debounce__default["default"](function (action) {
            if (action.disabled) {
                return;
            }
            switch (action.key) {
                case exports.ImageActionKey.ROTATE_LEFT:
                    _this.setState(function (prevState) { return ({
                        rotate: prevState.rotate - 90,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case exports.ImageActionKey.ROTATE_RIGHT:
                    _this.setState(function (prevState) { return ({
                        rotate: prevState.rotate + 90,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case exports.ImageActionKey.ZOOM_IN:
                    _this.setState(function (prevState) { return ({
                        scale: prevState.scale + 0.5,
                        tx: 0,
                        ty: 0
                    }); });
                    break;
                case exports.ImageActionKey.ZOOM_OUT:
                    _this.setState(function (prevState) {
                        return prevState.scale - 0.5 > 0
                            ? { scale: prevState.scale - 0.5, tx: 0, ty: 0 }
                            : null;
                    });
                    break;
                case exports.ImageActionKey.SCALE_ORIGIN:
                    _this.setState(function () { return ({ scale: 1, tx: 0, ty: 0 }); });
                    break;
            }
            if (action.onClick && typeof action.onClick === 'function') {
                action.onClick(_this);
            }
        }, 250, { leading: true, trailing: false });
        _this.scrollBar = React__default["default"].createRef();
        return _this;
    }
    ImageGallery.prototype.galleryMainRef = function (ref) {
        var _a, _b;
        if (ref) {
            ref.addEventListener('wheel', this.onWheelScroll, {
                passive: false
            });
            ref.addEventListener('mousedown', this.onMouseDown);
        }
        else {
            (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.removeEventListener('wheel', this.onWheelScroll);
            (_b = this.galleryMain) === null || _b === void 0 ? void 0 : _b.removeEventListener('mousedown', this.onMouseDown);
        }
        this.galleryMain = ref;
    };
    ImageGallery.prototype.onWheelScroll = function (event) {
        var _a;
        var showToolbar = (_a = this.state) === null || _a === void 0 ? void 0 : _a.showToolbar;
        if (!showToolbar) {
            return;
        }
        event.preventDefault();
        /** 向上滚动放大，向下滚动缩小 */
        if (event.deltaY > 0) {
            this.handleToolbarAction({ key: 'zoomOut' });
        }
        else if (event.deltaY < 0) {
            this.handleToolbarAction({ key: 'zoomIn' });
        }
    };
    ImageGallery.prototype.onMouseDown = function (event) {
        var _a;
        var isLeftButton = (event.button === 1 && window.event !== null) || event.button === 0;
        if (!isLeftButton || event.defaultPrevented)
            return;
        event.preventDefault();
        (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.classList.add('is-dragging');
        document.body.addEventListener('mousemove', this.onMouseMove);
        document.body.addEventListener('mouseup', this.onMouseUp);
        this.startX = event.clientX;
        this.startY = event.clientY;
        this.startTx = this.state.tx;
        this.startTy = this.state.ty;
    };
    ImageGallery.prototype.onMouseMove = function (event) {
        this.setState({
            tx: this.startTx + event.clientX - this.startX,
            ty: this.startTy + event.clientY - this.startY
        });
    };
    ImageGallery.prototype.onMouseUp = function () {
        var _a;
        (_a = this.galleryMain) === null || _a === void 0 ? void 0 : _a.classList.remove('is-dragging');
        document.body.removeEventListener('mousemove', this.onMouseMove);
        document.body.removeEventListener('mouseup', this.onMouseUp);
    };
    ImageGallery.prototype.handleImageEnlarge = function (info) {
        var actions = this.props.actions;
        var validActionKeys = Object.values(exports.ImageActionKey);
        this.setState({
            isOpened: true,
            tx: 0,
            ty: 0,
            rotate: 0,
            scale: 1,
            items: info.list ? info.list : [info],
            index: info.index || 0,
            /* children组件可以控制工具栏的展示 */
            showToolbar: !!info.showToolbar,
            enlargeWithGallary: info.enlargeWithGallary,
            imageGallaryClassName: info.imageGallaryClassName,
            /** 外部传入合法key值的actions才会生效 */
            actions: Array.isArray(info.toolbarActions)
                ? info.toolbarActions.filter(function (action) {
                    return validActionKeys.includes(action === null || action === void 0 ? void 0 : action.key);
                })
                : actions,
            scrollBarLeading: true,
            scrollBarTrailing: false
        });
    };
    ImageGallery.prototype.resetImageAction = function () {
        this.setState({ scale: 1, rotate: 0 });
    };
    ImageGallery.prototype.close = function () {
        this.setState({
            isOpened: false
        });
        this.resetImageAction();
    };
    ImageGallery.prototype.prev = function () {
        var index = this.state.index;
        this.setState({ index: index - 1 });
        this.resetImageAction();
    };
    ImageGallery.prototype.next = function () {
        var index = this.state.index;
        this.setState({ index: index + 1 });
        this.resetImageAction();
    };
    ImageGallery.prototype.handleItemClick = function (e) {
        var index = parseInt(e.currentTarget.getAttribute('data-index'), 10);
        this.setState({ index: index });
        this.resetImageAction();
    };
    ImageGallery.prototype.handleModalEntered = function () {
        if (this.scrollBar.current) {
            var item = this.scrollBar.current.querySelector("div[data-index=\"".concat(this.state.index, "\"]"));
            item === null || item === void 0 ? void 0 : item.scrollIntoView({
                behavior: 'smooth'
            });
        }
    };
    ImageGallery.prototype.handleBarScroll = function () {
        var scrollBar = this.scrollBar.current;
        var inner = scrollBar.firstElementChild;
        this.setState({
            scrollBarLeading: scrollBar.scrollLeft === 0,
            scrollBarTrailing: scrollBar.offsetWidth + scrollBar.scrollLeft >= inner.offsetWidth
        });
    };
    ImageGallery.prototype.scroll = function (direction) {
        if (direction === void 0) { direction = 1; }
        var scrollBar = this.scrollBar.current;
        var inner = scrollBar.firstElementChild;
        var gap = inner.offsetWidth - scrollBar.offsetWidth;
        scrollBar.scrollTo({
            left: scrollBar.scrollLeft + gap * 0.1 * direction,
            top: 0,
            behavior: 'smooth'
        });
        var timer = setInterval(function () {
            scrollBar.scrollTo({
                left: scrollBar.scrollLeft + 5 * direction,
                top: 0,
                behavior: 'smooth'
            });
        }, 50);
        var onMouseUp = function () {
            document.body.removeEventListener('mouseup', onMouseUp);
            clearInterval(timer);
        };
        document.body.addEventListener('mouseup', onMouseUp);
    };
    ImageGallery.prototype.scrollRight = function () {
        this.scroll(1);
    };
    ImageGallery.prototype.scrollLeft = function () {
        this.scroll(-1);
    };
    ImageGallery.prototype.renderToolbar = function (actions) {
        var _this = this;
        var _a = this.props, cx = _a.classnames, __ = _a.translate, className = _a.className;
        var scale = this.state.scale;
        return (_J$X_("div", { className: cx('ImageGallery-toolbar', className) }, actions.map(function (action) { return (_J$X_("div", { className: cx('ImageGallery-toolbar-action', {
                'is-disabled': action.disabled ||
                    (action.key === exports.ImageActionKey.ZOOM_OUT && scale - 0.5 <= 0)
            }), key: action.key, onClick: function () { return _this.handleToolbarAction(action); } },
            _J$X_("a", { className: cx('ImageGallery-toolbar-action-icon'), "data-tooltip": __(action.label), "data-position": "top" }, React__default["default"].isValidElement(action.icon) ? (React__default["default"].cloneElement(action.icon, {
                className: cx('icon', action.iconClassName)
            })) : (_J$X_(icons.Icon, { icon: action.icon, className: cx('icon', action.iconClassName) }))))); })));
    };
    ImageGallery.prototype.render = function () {
        var _this = this;
        var _a = this.props, children = _a.children, cx = _a.classnames, modalContainer = _a.modalContainer;
        var _b = this.state, index = _b.index, items = _b.items, rotate = _b.rotate, scale = _b.scale, tx = _b.tx, ty = _b.ty, showToolbar = _b.showToolbar, enlargeWithGallary = _b.enlargeWithGallary, actions = _b.actions, imageGallaryClassName = _b.imageGallaryClassName, scrollBarLeading = _b.scrollBarLeading, scrollBarTrailing = _b.scrollBarTrailing;
        var __ = this.props.translate;
        return (_J$X_(React__default["default"].Fragment, null,
            React__default["default"].cloneElement(children, {
                onImageEnlarge: this.handleImageEnlarge
            }),
            _J$X_(Modal["default"], { closeOnEsc: true, closeOnOutside: true, size: "full", onHide: this.close, show: this.state.isOpened, contentClassName: cx('ImageGallery', imageGallaryClassName), container: modalContainer, onEntered: this.handleModalEntered },
                _J$X_("a", { "data-tooltip": __('Dialog.close'), "data-position": "left", className: cx('ImageGallery-close'), onClick: this.close },
                    _J$X_(icons.Icon, { icon: "close", className: "icon" })),
                ~index && items[index] ? (_J$X_(React__default["default"].Fragment, null,
                    _J$X_("div", { className: cx('ImageGallery-title') }, items[index].title),
                    items[index].caption ? (_J$X_("div", { className: cx('ImageGallery-caption') }, items[index].caption)) : null,
                    _J$X_("div", { className: cx('ImageGallery-main'), ref: this.galleryMainRef },
                        _J$X_("img", { draggable: false, src: items[index].originalSrc, style: {
                                transform: "translate(".concat(tx, "px, ").concat(ty, "px) scale(").concat(scale, ") rotate(").concat(rotate, "deg)")
                            } }),
                        showToolbar && Array.isArray(actions) && actions.length > 0
                            ? this.renderToolbar(actions)
                            : null,
                        items.length > 1 && enlargeWithGallary !== false ? (_J$X_(React__default["default"].Fragment, null,
                            _J$X_("a", { className: cx('ImageGallery-prevBtn', index <= 0 ? 'is-disabled' : ''), onClick: this.prev },
                                _J$X_(icons.Icon, { icon: "prev", className: "icon", iconContent: "ImageGallery-prevBtn" })),
                            _J$X_("a", { className: cx('ImageGallery-nextBtn', index >= items.length - 1 ? 'is-disabled' : ''), onClick: this.next },
                                _J$X_(icons.Icon, { icon: "next", className: "icon", iconContent: "ImageGallery-nextBtn" })))) : null))) : null,
                items.length > 1 && enlargeWithGallary !== false ? (_J$X_("div", { className: cx('ImageGallery-footer') },
                    _J$X_("a", { className: cx('ImageGallery-prevList', scrollBarLeading ? 'is-disabled' : ''), onMouseDown: this.scrollLeft },
                        _J$X_(icons.Icon, { icon: "prev", className: "icon" })),
                    _J$X_("div", { className: cx('ImageGallery-itemsWrap'), ref: this.scrollBar, onScroll: this.handleBarScroll },
                        _J$X_("div", { className: cx('ImageGallery-items') }, items.map(function (item, i) { return (_J$X_("div", { key: i, "data-index": i, onClick: _this.handleItemClick, className: cx('ImageGallery-item', i === index ? 'is-active' : '') },
                            _J$X_("img", { src: item.src }))); }))),
                    _J$X_("a", { className: cx('ImageGallery-nextList', scrollBarTrailing ? 'is-disabled' : ''), onMouseDown: this.scrollRight },
                        _J$X_(icons.Icon, { icon: "next", className: "icon" })))) : null)));
    };
    ImageGallery.defaultProps = {
        actions: [
            {
                key: exports.ImageActionKey.ROTATE_LEFT,
                icon: 'rotate-left',
                label: 'rotate.left'
            },
            {
                key: exports.ImageActionKey.ROTATE_RIGHT,
                icon: 'rotate-right',
                label: 'rotate.right'
            },
            { key: exports.ImageActionKey.ZOOM_IN, icon: 'zoom-in', label: 'zoomIn' },
            { key: exports.ImageActionKey.ZOOM_OUT, icon: 'zoom-out', label: 'zoomOut' },
            {
                key: exports.ImageActionKey.SCALE_ORIGIN,
                icon: 'scale-origin',
                label: 'scale.origin'
            }
        ]
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [HTMLDivElement]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "galleryMainRef", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [WheelEvent]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onWheelScroll", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [MouseEvent]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseDown", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [MouseEvent]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseMove", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "onMouseUp", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleImageEnlarge", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "close", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "prev", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "next", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleItemClick", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleModalEntered", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "handleBarScroll", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "scrollRight", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], ImageGallery.prototype, "scrollLeft", null);
    return ImageGallery;
}(React__default["default"].Component));
var ImageGallery$1 = amisCore.themeable(amisCore.localeable(ImageGallery));

exports.ImageGallery = ImageGallery;
exports["default"] = ImageGallery$1;
