"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextSelectionTooltip = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const uikit_1 = require("@gravity-ui/uikit");
const lodash_1 = require("../../../lodash.js");
const memo_1 = require("../../../react-utils/memo.js");
const toolbar_1 = require("../../../toolbar/index.js");
const ToolbarRerender_1 = require("../../../toolbar/ToolbarRerender.js");
const ToolbarMemoized = (0, memo_1.typedMemo)(toolbar_1.Toolbar);
const KEY_SEP = '|||';
const TextSelectionTooltip = function TextSelectionTooltip({ popupAnchor, popupPlacement, popupOnOpenChange, config, focus, editor, onClick, editorView, }) {
    const [conditionKey, setConditionKey] = (0, react_1.useState)(() => calcConditionKey(config, editor, editorView));
    (0, react_1.useEffect)(() => {
        const newKey = calcConditionKey(config, editor, editorView);
        if (conditionKey !== newKey)
            setConditionKey(newKey);
    });
    const toolbarData = (0, react_1.useMemo)(() => {
        const results = conditionKey.split(KEY_SEP);
        let idx = 0;
        return config
            .map((groupData) => groupData.filter(() => results[idx++] === 'true'))
            .filter((groupData) => Boolean(groupData.length));
    }, [config, conditionKey]);
    return ((0, jsx_runtime_1.jsx)(uikit_1.Popup, { open: true, className: (0, uikit_1.sp)({ p: '0.5' }), placement: popupPlacement, anchorElement: popupAnchor, onOpenChange: popupOnOpenChange, children: (0, jsx_runtime_1.jsx)(ToolbarRerender_1.ToolbarWrapToContext, { editor: editor, children: (0, jsx_runtime_1.jsx)(ToolbarMemoized, { focus: focus, editor: editor, onClick: onClick, data: toolbarData, qa: "g-md-toolbar-selection" }) }) }));
};
exports.TextSelectionTooltip = TextSelectionTooltip;
function calcConditionKey(config, editor, editorView) {
    return config
        .flatMap((groupData) => groupData.map((item) => {
        const { condition } = item;
        if (condition === 'enabled')
            return item.isEnable(editor);
        if ((0, lodash_1.isFunction)(condition))
            return condition(editorView.state);
        return true;
    }))
        .join(KEY_SEP);
}
//# sourceMappingURL=TextSelectionTooltip.js.map
