var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import React from 'react';
import debounce from 'lodash.debounce';
import { isBrowser } from '../../lib/globalObject.js';
import * as LayoutEvents from '../../lib/LayoutEvents.js';
import { Spinner } from '../Spinner/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { ZIndex } from '../../internal/ZIndex/index.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { isTestEnv } from '../../lib/currentEnvironment.js';
import { TaskWithDelayAndMinimalDuration } from '../../lib/taskWithDelayAndMinimalDuration.js';
import { getTabbableElements } from '../../lib/dom/tabbableHelpers.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { getDOMRect } from '../../lib/dom/getDOMRect.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Loader.styles.js';
var types = ['mini', 'normal', 'big'];
export var LoaderDataTids = {
    idle: 'Loader__Idle',
    veil: 'Loader__Veil',
    spinner: 'Loader__Spinner',
};
/**
 * С помощью лоадера можно отобразить процесс выполнения задачи.
 * Лоадер принимает в качестве дочернего элемента другой компонент или контент, который будет показан на экране.
 * Когда происходит загрузка, поверх этого компонента или контента будет отображаться [Спиннер](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_display-data-spinner--docs).
 */
var Loader = /** @class */ (function (_super) {
    __extends(Loader, _super);
    function Loader(props) {
        var _this = _super.call(this, props) || this;
        _this.getProps = createPropsGetter(Loader_1.defaultProps);
        _this.childrenRef = function (element) {
            _this.childrenContainerNode = element;
        };
        _this.spinnerRef = function (element) {
            _this.spinnerContainerNode = element;
        };
        _this.checkSpinnerPosition = function () {
            if (!_this.spinnerContainerNode || !isBrowser(_this.globalObject)) {
                return;
            }
            var _a = getDOMRect(_this.spinnerContainerNode), containerTop = _a.top, containerRight = _a.right, containerBottom = _a.bottom, containerLeft = _a.left, containerHeight = _a.height, containerWidth = _a.width;
            var windowHeight = _this.globalObject.innerHeight;
            var windowWidth = _this.globalObject.innerWidth;
            // Если контейнер не больше высоты и не шире окна,
            // то просто выравниваем по центру
            if (windowHeight >= containerHeight && windowWidth >= containerWidth) {
                _this.setState({
                    isStickySpinner: false,
                    spinnerStyle: {},
                });
                return;
            }
            var spinnerStyle = {
                top: 30,
                right: 0,
                bottom: 30,
                left: 0,
            };
            // ПО ВЕРТИКАЛИ
            // Если верхний край контейнера ниже верхнего края окна,
            // то сдвигаем и лоадер
            if (containerTop > 0) {
                spinnerStyle.top = containerTop + 30;
            }
            // Если нижний край контейнера выше нижнего края окна,
            // то сдвигаем и лоадер
            if (containerBottom < windowHeight) {
                spinnerStyle.bottom = Math.abs(windowHeight - containerBottom) + 30;
            }
            // Если знаем высоту спиннера и нижний край контейнера поднимается
            // выше отступа на высоту спиннера, то убираем верхнюю позицию лоадера
            var spinnerHeight = getDOMRect(_this.spinnerNode).height;
            if (spinnerHeight && spinnerStyle.bottom >= windowHeight - spinnerHeight) {
                delete spinnerStyle.top;
            }
            // ПО ГОРИЗОНТАЛИ
            // Если левый край контейнера правее левого края окна,
            // то сдвигаем и лоадер
            if (containerLeft > 0) {
                spinnerStyle.left = containerLeft;
            }
            // Если правый край контейнера левее правого края окна,
            // то сдвигаем и лоадер
            if (containerRight < windowWidth) {
                spinnerStyle.right = windowWidth - containerRight;
            }
            _this.setState({
                isStickySpinner: true,
                spinnerStyle: spinnerStyle,
            });
        };
        _this.disableChildrenFocus = function () {
            if (!_this.childrenObserver) {
                _this.makeObservable();
            }
            var tabbableElements = getTabbableElements(_this.childrenContainerNode);
            tabbableElements.forEach(function (el) {
                if (!el.hasAttribute('origin-tabindex')) {
                    el.setAttribute('origin-tabindex', el.tabIndex.toString());
                }
                el.tabIndex = -1;
            });
        };
        _this.enableChildrenFocus = function () {
            var _a;
            _this.makeUnobservable();
            (_a = _this.globalObject.document) === null || _a === void 0 ? void 0 : _a.querySelectorAll('[origin-tabindex]').forEach(function (el) {
                var _a;
                el.setAttribute('tabindex', (_a = el.getAttribute('origin-tabindex')) !== null && _a !== void 0 ? _a : '0');
                el.removeAttribute('origin-tabindex');
            });
        };
        _this.makeObservable = function () {
            var target = _this.childrenContainerNode;
            if (!target || !_this.globalObject.MutationObserver) {
                return;
            }
            var config = {
                childList: true,
                subtree: true,
            };
            var observer = new _this.globalObject.MutationObserver(_this.disableChildrenFocus);
            observer.observe(target, config);
            _this.childrenObserver = observer;
        };
        _this.makeUnobservable = function () {
            var _a;
            (_a = _this.childrenObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
            _this.childrenObserver = null;
        };
        _this.spinnerContainerNode = null;
        _this.childrenContainerNode = null;
        _this.childrenObserver = null;
        _this.spinnerNode = null;
        _this.state = {
            isStickySpinner: false,
            isSpinnerVisible: false,
            isLoaderActive: false,
        };
        return _this;
    }
    Loader_1 = Loader;
    Loader.prototype.componentDidMount = function () {
        var _this = this;
        this.spinnerTask = new TaskWithDelayAndMinimalDuration({
            delayBeforeTaskStart: this.getProps().delayBeforeSpinnerShow,
            durationOfTask: this.getProps().minimalDelayBeforeSpinnerHide,
            taskStartCallback: function () { return _this.setState({ isSpinnerVisible: true }); },
            taskStopCallback: function () { return _this.setState({ isSpinnerVisible: false }); },
        });
        var active = this.getProps().active;
        this.checkSpinnerPosition();
        active && this.spinnerTask.start();
        this.layoutEvents = LayoutEvents.addListener(debounce(this.checkSpinnerPosition, 10), this.globalObject);
        if (active) {
            this.disableChildrenFocus();
        }
    };
    Loader.prototype.componentDidUpdate = function (prevProps, prevState) {
        var component = this.props.component;
        var _a = this.getProps(), active = _a.active, delayBeforeSpinnerShow = _a.delayBeforeSpinnerShow, minimalDelayBeforeSpinnerHide = _a.minimalDelayBeforeSpinnerHide;
        var isLoaderActive = this.state.isLoaderActive;
        if ((active && !prevProps.active) || prevProps.component !== component) {
            this.checkSpinnerPosition();
        }
        if (delayBeforeSpinnerShow !== prevProps.delayBeforeSpinnerShow ||
            minimalDelayBeforeSpinnerHide !== prevProps.minimalDelayBeforeSpinnerHide) {
            this.spinnerTask.update({
                delayBeforeTaskStart: delayBeforeSpinnerShow,
                durationOfTask: minimalDelayBeforeSpinnerHide,
            });
        }
        if (active !== prevProps.active) {
            active ? this.spinnerTask.start() : this.spinnerTask.stop();
        }
        if (isLoaderActive !== prevState.isLoaderActive) {
            if (isLoaderActive) {
                this.disableChildrenFocus();
            }
            else {
                this.enableChildrenFocus();
            }
        }
    };
    Loader.prototype.componentWillUnmount = function () {
        this.makeUnobservable();
        if (this.layoutEvents) {
            this.layoutEvents.remove();
        }
        this.spinnerTask.clearTask();
    };
    Loader.getDerivedStateFromProps = function (props, state) {
        if (props.active && !state.isLoaderActive) {
            return {
                isLoaderActive: true,
            };
        }
        if (state.isLoaderActive && !(props.active || state.isSpinnerVisible)) {
            return {
                isLoaderActive: false,
            };
        }
        return state;
    };
    Loader.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return _this.renderMain();
        }));
    };
    Loader.prototype.renderMain = function () {
        var _a;
        var _b = this.props, caption = _b.caption, component = _b.component;
        var type = this.getProps().type;
        var isLoaderActive = this.state.isLoaderActive;
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement("div", { className: this.styles.loader(), "data-tid": this.props['data-tid'] || (isLoaderActive ? LoaderDataTids.veil : LoaderDataTids.idle) },
                React.createElement(ZIndex, { applyZIndex: isLoaderActive, coverChildren: isLoaderActive, style: { height: '100%' }, wrapperRef: this.childrenRef }, this.props.children),
                isLoaderActive && (React.createElement(ZIndex, { wrapperRef: this.spinnerRef, className: this.cx((_a = {},
                        _a[this.styles.active(this.theme)] = isLoaderActive,
                        _a)) }, this.state.isSpinnerVisible && this.renderSpinner(type, caption, component))))));
    };
    Loader.prototype.renderSpinner = function (type, caption, component) {
        var _a;
        var _this = this;
        return (React.createElement("span", { "data-tid": LoaderDataTids.spinner, className: this.cx(this.styles.spinnerContainer(), (_a = {},
                _a[this.styles.spinnerContainerSticky()] = this.state.isStickySpinner,
                _a)), style: this.state.spinnerStyle },
            React.createElement("div", { className: this.styles.spinnerComponentWrapper(), ref: function (element) {
                    _this.spinnerNode = element;
                } }, component !== undefined ? component : React.createElement(Spinner, { type: type, caption: caption }))));
    };
    var Loader_1;
    Loader.__KONTUR_REACT_UI__ = 'Loader';
    Loader.displayName = 'Loader';
    Loader.defaultProps = {
        type: 'normal',
        active: false,
        delayBeforeSpinnerShow: isTestEnv ? 0 : 300,
        minimalDelayBeforeSpinnerHide: isTestEnv ? 0 : 1000,
    };
    Loader = Loader_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], Loader);
    return Loader;
}(React.Component));
export { Loader };
//# sourceMappingURL=Loader.js.map