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 { isElement } from '../../lib/react-is.js';
import { isKonturIcon } from '../../lib/utils.js';
import { isKeyArrowVertical, isKeyEnter, isKeySpace, someKeys } from '../../lib/events/keyboard/identifiers.js';
import * as LayoutEvents from '../../lib/LayoutEvents.js';
import { KeyListener } from '../../lib/events/keyListener.js';
import { PopupMenu } from '../../internal/PopupMenu/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { isTestEnv } from '../../lib/currentEnvironment.js';
import { ThemeFactory } from '../../lib/theming/ThemeFactory.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { getVisualStateDataAttributes } from '../../internal/CommonWrapper/utils/getVisualStateDataAttributes.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Kebab.styles.js';
import { KebabIcon } from './KebabIcon.js';
export var KebabDataTids = {
    caption: 'Kebab__caption',
};
/**
 * Кебаб-меню содержит действия с объектом.
 */
var Kebab = /** @class */ (function (_super) {
    __extends(Kebab, _super);
    function Kebab() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getProps = createPropsGetter(Kebab_1.defaultProps);
        _this.state = {
            focusedByTab: false,
            anchor: null,
        };
        _this.listener = {
            remove: function () { return undefined; },
        };
        _this.renderCaption = function (captionProps) {
            var disabled = _this.getProps().disabled;
            var size = _this.size;
            var handleCaptionKeyDown = function (event) {
                if (!disabled) {
                    _this.handleCaptionKeyDown(event, captionProps.openMenu);
                }
            };
            var handleCaptionClick = function () {
                if (!disabled) {
                    captionProps.toggleMenu();
                }
            };
            return (React.createElement("span", { role: "button", "data-tid": KebabDataTids.caption, tabIndex: disabled ? -1 : 0, onClick: handleCaptionClick, onKeyDown: handleCaptionKeyDown, onFocus: _this.handleFocus, onBlur: _this.handleBlur, className: _this.cx(_this.styles.kebab(_this.theme), size === 'small' && _this.styles.kebabSmall(_this.theme), size === 'medium' && _this.styles.kebabMedium(_this.theme), size === 'large' && _this.styles.kebabLarge(_this.theme), captionProps.opened && _this.styles.opened(_this.theme), disabled && _this.styles.disabled(), _this.state.focusedByTab && _this.styles.focused(_this.theme)), "aria-describedby": _this.props['aria-describedby'] }, _this.renderIcon()));
        };
        _this.handleCaptionKeyDown = function (e, openMenu) {
            if (someKeys(isKeyEnter, isKeySpace, isKeyArrowVertical)(e)) {
                e.preventDefault();
                openMenu(true);
            }
        };
        _this.handleChangeMenuState = function (isOpened, restoreFocus) {
            _this.setState({
                focusedByTab: !isOpened && restoreFocus,
            });
        };
        _this.handleFocus = function () {
            var _a, _b;
            if (!_this.props.disabled) {
                // focus event fires before keyDown eventlistener
                // so we should check tabPressed in async way
                (_b = (_a = _this.globalObject).requestAnimationFrame) === null || _b === void 0 ? void 0 : _b.call(_a, function () {
                    if (_this.keyListener.isTabPressed) {
                        _this.setState({ focusedByTab: true });
                    }
                });
            }
        };
        _this.handleBlur = function () {
            _this.setState({
                focusedByTab: false,
            });
        };
        return _this;
    }
    Kebab_1 = Kebab;
    Kebab.prototype.componentDidMount = function () {
        this.keyListener = new KeyListener(this.globalObject);
        /** addListener'у нужен колбэк в аргумент */
        this.listener = LayoutEvents.addListener(function () { return undefined; }, this.globalObject);
    };
    Kebab.prototype.componentWillUnmount = function () {
        this.listener.remove();
    };
    Kebab.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return (React.createElement(ThemeContext.Provider, { value: ThemeFactory.create({
                    popupMargin: theme.kebabMargin,
                }, theme) }, _this.renderMain()));
        }));
    };
    Kebab.prototype.renderMain = function () {
        var disabled = this.props.disabled;
        var _a = this.getProps(), positions = _a.positions, disableAnimations = _a.disableAnimations, onOpen = _a.onOpen, onClose = _a.onClose;
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props, getVisualStateDataAttributes({ disabled: disabled })),
            React.createElement(PopupMenu, { id: this.props.id, popupHasPin: false, preventIconsOffset: this.props.preventIconsOffset, positions: positions, onChangeMenuState: this.handleChangeMenuState, caption: this.renderCaption, disableAnimations: disableAnimations, menuMaxHeight: this.props.menuMaxHeight, onOpen: onOpen, onClose: onClose, popupMenuId: this.props.popupMenuId, "aria-label": this.props['aria-label'] }, !disabled && this.props.children)));
    };
    Kebab.prototype.renderIcon = function () {
        var _a, _b;
        var _c = this.getProps().icon, icon = _c === void 0 ? React.createElement(KebabIcon, null) : _c;
        if (isElement(icon) && isKonturIcon(icon)) {
            var iconProps = icon.props;
            var sizes = {
                small: parseInt(this.theme.kebabIconSizeSmall),
                medium: parseInt(this.theme.kebabIconSizeMedium),
                large: parseInt(this.theme.kebabIconSizeLarge),
            };
            return React.cloneElement(icon, {
                size: (_a = iconProps.size) !== null && _a !== void 0 ? _a : sizes[this.size],
                color: (_b = iconProps.color) !== null && _b !== void 0 ? _b : this.theme.kebabIconColor,
            });
        }
        return icon;
    };
    var Kebab_1;
    Kebab.__KONTUR_REACT_UI__ = 'Kebab';
    Kebab.displayName = 'Kebab';
    Kebab.defaultProps = {
        onOpen: function () { return undefined; },
        onClose: function () { return undefined; },
        positions: ['bottom left', 'bottom right', 'top left', 'top right'],
        disableAnimations: isTestEnv,
    };
    Kebab = Kebab_1 = __decorate([
        withRenderEnvironment,
        rootNode,
        withSize
    ], Kebab);
    return Kebab;
}(React.Component));
export { Kebab };
//# sourceMappingURL=Kebab.js.map