"use strict";
/*---------------------------------------------------------------------------------------------
 * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
 * See LICENSE.md in the project root for license terms and full copyright notice.
 *--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module ChildWindowManager
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReparentedPopoutWidget = void 0;
require("./ReparentedPopoutWidget.scss");
const React = require("react");
const core_react_1 = require("@itwin/core-react");
const usePopoutsStore_1 = require("./usePopoutsStore");
/** @internal */
function ReparentedPopoutWidget({ widgetId, }) {
    const setPopout = (0, usePopoutsStore_1.usePopoutsStore)((state) => state.setPopout);
    const setPopoutRef = React.useCallback((instance) => {
        setPopout(widgetId, instance ?? undefined);
    }, [setPopout, widgetId]);
    const autoCloseRef = useAutoClosePopovers(widgetId);
    const ref = (0, core_react_1.useRefs)(setPopoutRef, autoCloseRef);
    return (React.createElement("div", { className: "uifw-preview-reparentPopoutWidgets-reparentedPopoutWidget", "data-widget-id": widgetId, ref: ref }));
}
exports.ReparentedPopoutWidget = ReparentedPopoutWidget;
/** A workaround to close floating/popover elements when a popout widget is closed.
 * There are some issues with the popover alignment, especially if the tab is not active (popover target is not rendered) after closing the popout.
 */
function useAutoClosePopovers(widgetContainerId) {
    const ref = React.useRef(null);
    const onClosePopoutWidget = (0, usePopoutsStore_1.usePopoutsStore)((state) => state.onClosePopoutWidget);
    React.useEffect(() => {
        const element = ref.current;
        if (!element)
            return;
        return onClosePopoutWidget.addListener(({ windowId }) => {
            if (windowId !== widgetContainerId)
                return;
            element.dispatchEvent(new MouseEvent("mousedown"));
            element.dispatchEvent(new PointerEvent("pointerdown"));
        });
    }, [widgetContainerId, onClosePopoutWidget]);
    return ref;
}
//# sourceMappingURL=ReparentedPopoutWidget.js.map