import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from 'react';
import { Popup, sp } from '@gravity-ui/uikit';
import { isFunction } from "../../../lodash.js";
import { typedMemo } from "../../../react-utils/memo.js";
import { Toolbar } from "../../../toolbar/index.js";
import { ToolbarWrapToContext } from "../../../toolbar/ToolbarRerender.js";
const ToolbarMemoized = typedMemo(Toolbar);
const KEY_SEP = '|||';
export const TextSelectionTooltip = function TextSelectionTooltip({ popupAnchor, popupPlacement, popupOnOpenChange, config, focus, editor, onClick, editorView, }) {
    const [conditionKey, setConditionKey] = useState(() => calcConditionKey(config, editor, editorView));
    useEffect(() => {
        const newKey = calcConditionKey(config, editor, editorView);
        if (conditionKey !== newKey)
            setConditionKey(newKey);
    });
    const toolbarData = 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 (_jsx(Popup, { open: true, className: sp({ p: '0.5' }), placement: popupPlacement, anchorElement: popupAnchor, onOpenChange: popupOnOpenChange, children: _jsx(ToolbarWrapToContext, { editor: editor, children: _jsx(ToolbarMemoized, { focus: focus, editor: editor, onClick: onClick, data: toolbarData, qa: "g-md-toolbar-selection" }) }) }));
};
function calcConditionKey(config, editor, editorView) {
    return config
        .flatMap((groupData) => groupData.map((item) => {
        const { condition } = item;
        if (condition === 'enabled')
            return item.isEnable(editor);
        if (isFunction(condition))
            return condition(editorView.state);
        return true;
    }))
        .join(KEY_SEP);
}
//# sourceMappingURL=TextSelectionTooltip.js.map
