"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 Widget
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.PopoutThemeProvider = void 0;
require("./PopoutThemeProvider.scss");
const React = require("react");
const itwinui_react_1 = require("@itwin/itwinui-react");
const ContentRenderer_1 = require("../../layout/widget/ContentRenderer");
const LayoutStore_1 = require("../../layout/base/LayoutStore");
const TabLocation_1 = require("../../layout/state/TabLocation");
const usePopoutsStore_1 = require("./usePopoutsStore");
/** Theme provider is required to open floating/popover elements in a popout widget window (instead of a main window).
 * @note iTwinUI v2 `ThemeProvider` is not used because of https://github.com/iTwin/appui/issues/612
 * @internal
 */
function PopoutThemeProvider({ children }) {
    const tabId = React.useContext(ContentRenderer_1.TabIdContext);
    const layoutStore = (0, LayoutStore_1.useLayoutStore)();
    const stateRef = React.useRef(layoutStore.getState());
    React.useEffect(() => layoutStore.subscribe((state) => (stateRef.current = state)), [layoutStore]);
    const portalContainer = (0, usePopoutsStore_1.usePopoutsStore)((state) => {
        if (!tabId)
            return undefined;
        const tabLocation = (0, TabLocation_1.getTabLocation)(stateRef.current, tabId);
        if (!tabLocation)
            return undefined;
        if (!(0, TabLocation_1.isPopoutTabLocation)(tabLocation))
            return undefined;
        const popout = state.popouts[tabLocation.popoutWidgetId];
        if (!popout)
            return undefined;
        const container = popout.ownerDocument.querySelector(".uifw-childwindow-internalChildWindowManager_portalContainer");
        return container ?? undefined;
    });
    return (React.createElement(itwinui_react_1.ThemeProvider, { portalContainer: portalContainer, className: "uifw-preview-reparentPopoutWidgets-popoutThemeProvider" }, children));
}
exports.PopoutThemeProvider = PopoutThemeProvider;
//# sourceMappingURL=PopoutThemeProvider.js.map