"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 Frontstage
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useItemsManager = exports.useFrontstageManager = exports.getFrontstageStateSettingName = exports.FRONTSTAGE_SETTINGS_NAMESPACE = exports.useSaveFrontstageSettings = exports.useSavedFrontstageState = exports.expandWidget = exports.showWidget = exports.isPanelCollapsed = exports.packNineZoneState = exports.restoreNineZoneState = exports.initializeNineZoneState = exports.stateVersion = exports.initializePanel = exports.isFrontstageStateSettingResult = exports.addPanelWidgets = exports.getPanelSectionWidgets = exports.getWidgetId = exports.addMissingWidgets = exports.appendWidgets = exports.addWidgets = exports.useLabels = exports.ActiveFrontstageDefProvider = exports.WidgetPanelsFrontstage = exports.useNineZoneDispatch = exports.useUpdateNineZoneSize = exports.useLayoutStore = void 0;
// cSpell:ignore popout
require("./Frontstage.scss");
const immer_1 = require("immer");
const React = require("react");
const react_dom_1 = require("react-dom");
const core_bentley_1 = require("@itwin/core-bentley");
const core_react_1 = require("@itwin/core-react");
const components_react_1 = require("@itwin/components-react");
const appui_layout_react_1 = require("@itwin/appui-layout-react");
const FrontstageDef_1 = require("../frontstage/FrontstageDef");
const StagePanelDef_1 = require("../stagepanels/StagePanelDef");
const UiFramework_1 = require("../UiFramework");
const useUiStateStorage_1 = require("../uistate/useUiStateStorage");
const Content_1 = require("./Content");
const FrontstageContent_1 = require("./FrontstageContent");
const ModalFrontstageComposer_1 = require("./ModalFrontstageComposer");
const StatusBar_1 = require("./StatusBar");
const Tab_1 = require("./Tab");
const Toolbars_1 = require("./Toolbars");
const ToolSettings_1 = require("./ToolSettings");
const useEscapeSetFocusToHome_1 = require("../hooks/useEscapeSetFocusToHome");
const react_redux_1 = require("react-redux");
const useUiVisibility_1 = require("../hooks/useUiVisibility");
const core_frontend_1 = require("@itwin/core-frontend");
const FloatingWidget_1 = require("./FloatingWidget");
const InternalFrontstageManager_1 = require("../frontstage/InternalFrontstageManager");
const WidgetState_1 = require("../widgets/WidgetState");
const StagePanelSection_1 = require("../stagepanels/StagePanelSection");
const StagePanelLocation_1 = require("../stagepanels/StagePanelLocation");
const UiItemsManager_1 = require("../ui-items-provider/UiItemsManager");
function WidgetPanelsFrontstageComponent() {
    const activeModalFrontstageInfo = (0, ModalFrontstageComposer_1.useActiveModalFrontstageInfo)();
    const uiIsVisible = (0, useUiVisibility_1.useUiVisibility)();
    return (React.createElement(React.Fragment, null,
        React.createElement(ToolSettings_1.WidgetPanelsToolSettings, null),
        React.createElement(components_react_1.ToolbarPopupAutoHideContext.Provider, { value: !uiIsVisible },
            React.createElement(ModalFrontstageComposer_1.ModalFrontstageComposer, { stageInfo: activeModalFrontstageInfo }),
            React.createElement(appui_layout_react_1.WidgetPanels, { className: "uifw-widgetPanels", centerContent: React.createElement(Toolbars_1.WidgetPanelsToolbars, null) },
                React.createElement(FrontstageContent_1.WidgetPanelsFrontstageContent, null)),
            React.createElement(StatusBar_1.WidgetPanelsStatusBar, null),
            React.createElement(appui_layout_react_1.FloatingWidgets, null))));
}
const widgetContent = React.createElement(Content_1.WidgetContent, null);
const toolSettingsContent = React.createElement(ToolSettings_1.ToolSettingsContent, null);
const widgetPanelsFrontstage = React.createElement(WidgetPanelsFrontstageComponent, null);
/** @internal */
function useLayoutStore(frontstageDef) {
    const layoutStore = React.useMemo(() => (0, appui_layout_react_1.createLayoutStore)(frontstageDef?.nineZoneState), [frontstageDef]);
    React.useEffect(() => {
        return InternalFrontstageManager_1.InternalFrontstageManager.onFrontstageNineZoneStateChangedEvent.addListener((args) => {
            if (args.frontstageDef !== frontstageDef)
                return;
            (0, react_dom_1.unstable_batchedUpdates)(() => {
                // https://github.com/pmndrs/zustand/blob/main/docs/guides/event-handler-in-pre-react-18.md
                layoutStore.setState(args.state || defaultNineZone);
            });
        });
    }, [frontstageDef, layoutStore]);
    return layoutStore;
}
exports.useLayoutStore = useLayoutStore;
/** Update in-memory NineZoneState of newly activated frontstage with up to date size.
 * @internal
 */
function useUpdateNineZoneSize(frontstageDef) {
    React.useEffect(() => {
        const size = InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize;
        const state = frontstageDef.nineZoneState;
        if (!size || !state)
            return;
        frontstageDef.dispatch({
            type: "RESIZE",
            size: {
                height: size.height,
                width: size.width,
            },
        });
    }, [frontstageDef]);
}
exports.useUpdateNineZoneSize = useUpdateNineZoneSize;
/** @internal */
function useNineZoneDispatch(frontstageDef) {
    return React.useMemo(() => frontstageDef.dispatch, [frontstageDef]);
}
exports.useNineZoneDispatch = useNineZoneDispatch;
/** @internal */
function WidgetPanelsFrontstage() {
    const frontstageDef = (0, FrontstageDef_1.useActiveFrontstageDef)();
    const layout = useLayoutStore(frontstageDef);
    React.useEffect(() => {
        const triggerWidowCloseProcessing = () => {
            frontstageDef && frontstageDef.setIsApplicationClosing(true);
        };
        window.addEventListener("unload", triggerWidowCloseProcessing);
        return () => {
            window.removeEventListener("unload", triggerWidowCloseProcessing);
        };
    }, [frontstageDef]);
    if (!frontstageDef)
        return null;
    return (React.createElement(ActiveFrontstageDefProvider, { frontstageDef: frontstageDef, layout: layout }));
}
exports.WidgetPanelsFrontstage = WidgetPanelsFrontstage;
const defaultNineZone = (0, appui_layout_react_1.createNineZoneState)();
const tabElement = React.createElement(Tab_1.WidgetPanelsTab, null);
const floatingWidgetElement = React.createElement(FloatingWidget_1.FloatingWidget, null);
/** @internal */
function ActiveFrontstageDefProvider({ frontstageDef, layout, }) {
    const dispatch = useNineZoneDispatch(frontstageDef);
    useUpdateNineZoneSize(frontstageDef);
    useSavedFrontstageState(frontstageDef);
    useSaveFrontstageSettings(frontstageDef, layout);
    useItemsManager(frontstageDef);
    const labels = useLabels();
    const uiIsVisible = (0, useUiVisibility_1.useUiVisibility)();
    const showWidgetIcon = (0, react_redux_1.useSelector)((state) => {
        const frameworkState = state[UiFramework_1.UiFramework.frameworkStateKey];
        return !!frameworkState.configurableUiState.showWidgetIcon;
    });
    const autoCollapseUnpinnedPanels = (0, react_redux_1.useSelector)((state) => {
        const frameworkState = state[UiFramework_1.UiFramework.frameworkStateKey];
        return !!frameworkState.configurableUiState.autoCollapseUnpinnedPanels;
    });
    const animateToolSettings = (0, react_redux_1.useSelector)((state) => {
        const frameworkState = state[UiFramework_1.UiFramework.frameworkStateKey];
        return !!frameworkState.configurableUiState.animateToolSettings;
    });
    const useToolAsToolSettingsLabel = (0, react_redux_1.useSelector)((state) => {
        const frameworkState = state[UiFramework_1.UiFramework.frameworkStateKey];
        return !!frameworkState.configurableUiState.useToolAsToolSettingsLabel;
    });
    useFrontstageManager(frontstageDef, useToolAsToolSettingsLabel);
    const handleKeyDown = (0, useEscapeSetFocusToHome_1.useEscapeSetFocusToHome)();
    return (React.createElement("div", { className: "uifw-widgetPanels-frontstage", onKeyDown: handleKeyDown, role: "presentation" },
        React.createElement(appui_layout_react_1.NineZone, { dispatch: dispatch, labels: labels, layout: layout, tab: tabElement, floatingWidget: floatingWidgetElement, showWidgetIcon: showWidgetIcon, autoCollapseUnpinnedPanels: autoCollapseUnpinnedPanels, toolSettingsContent: toolSettingsContent, widgetContent: widgetContent, animateDockedToolSettings: animateToolSettings, uiIsVisible: uiIsVisible }, widgetPanelsFrontstage)));
}
exports.ActiveFrontstageDefProvider = ActiveFrontstageDefProvider;
/** @internal */
function useLabels() {
    return React.useMemo(() => ({
        dockToolSettingsTitle: UiFramework_1.UiFramework.translate("widget.tooltips.dockToolSettings"),
        moreWidgetsTitle: UiFramework_1.UiFramework.translate("widget.tooltips.moreWidgets"),
        moreToolSettingsTitle: UiFramework_1.UiFramework.translate("widget.tooltips.moreToolSettings"),
        pinPanelTitle: UiFramework_1.UiFramework.translate("widget.tooltips.pinPanel"),
        resizeGripTitle: UiFramework_1.UiFramework.translate("widget.tooltips.resizeGrip"),
        sendWidgetHomeTitle: UiFramework_1.UiFramework.translate("widget.tooltips.sendHome"),
        toolSettingsHandleTitle: UiFramework_1.UiFramework.translate("widget.tooltips.toolSettingsHandle"),
        unpinPanelTitle: UiFramework_1.UiFramework.translate("widget.tooltips.unpinPanel"),
        popoutActiveTab: UiFramework_1.UiFramework.translate("widget.tooltips.popoutActiveTab"),
    }), []);
}
exports.useLabels = useLabels;
function toTabArgs(widget) {
    const label = getWidgetLabel(widget.label);
    const args = {
        allowedPanelTargets: widget.allowedPanelTargets?.map((location) => (0, StagePanelDef_1.toPanelSide)(location)),
        hideWithUiWhenFloating: !!widget.hideWithUiWhenFloating,
        canPopout: widget.canPopout,
        iconSpec: widget.iconSpec,
        isFloatingWidgetResizable: widget.isFloatingStateWindowResizable,
        label,
        preferredFloatingWidgetSize: widget.defaultFloatingSize,
        preferredPanelWidgetSize: widget.preferredPanelSize,
    };
    return args;
}
/** @internal */
function addWidgets(state, widgets, side, widgetId) {
    const visibleWidgets = widgets.filter((w) => w.isVisible && w.defaultState !== WidgetState_1.WidgetState.Floating);
    if (visibleWidgets.length === 0)
        return state;
    const tabs = new Array();
    for (const widget of visibleWidgets) {
        state = (0, appui_layout_react_1.addTab)(state, widget.id, toTabArgs(widget));
        tabs.push(widget.id);
    }
    const activeWidget = visibleWidgets.find((widget) => widget.isActive);
    const minimized = false;
    // istanbul ignore else
    if (activeWidget?.defaultState !== WidgetState_1.WidgetState.Floating) {
        state = (0, appui_layout_react_1.addPanelWidget)(state, side, widgetId, tabs, {
            activeTabId: activeWidget ? activeWidget.id : tabs[0],
            minimized,
        });
    }
    return state;
}
exports.addWidgets = addWidgets;
/** @internal */
// istanbul ignore next
function appendWidgets(state, widgetDefs, location, section) {
    const side = (0, StagePanelDef_1.toPanelSide)(location);
    // Add missing widget tabs.
    for (const widgetDef of widgetDefs) {
        const saveTab = state.tabs[widgetDef.id];
        const preferredPanelWidgetSize = saveTab
            ? saveTab.preferredPanelWidgetSize
            : widgetDef.preferredPanelSize;
        const preferredFloatingWidgetSize = saveTab
            ? saveTab.preferredFloatingWidgetSize
            : widgetDef.defaultFloatingSize;
        // if a defaultFloatingSize is specified then this mean the widget can't determine its intrinsic size and must be explicitly sized
        const userSized = saveTab
            ? saveTab.userSized ||
                (!!widgetDef.defaultFloatingSize &&
                    !!saveTab.preferredFloatingWidgetSize)
            : !!widgetDef.defaultFloatingSize;
        state = (0, appui_layout_react_1.addTab)(state, widgetDef.id, {
            ...toTabArgs(widgetDef),
            preferredFloatingWidgetSize,
            preferredPanelWidgetSize,
            userSized,
        });
        const savedTab = state.savedTabs.byId[widgetDef.id];
        if (savedTab) {
            state = (0, appui_layout_react_1.addRemovedTab)(state, widgetDef.id);
        }
        else if (widgetDef.isFloatingStateSupported &&
            widgetDef.defaultState === WidgetState_1.WidgetState.Floating) {
            const floatingContainerId = widgetDef.floatingContainerId
                ? widgetDef.floatingContainerId
                : (0, appui_layout_react_1.getUniqueId)();
            const widgetContainerId = getWidgetId(location, section);
            const home = {
                side,
                widgetId: widgetContainerId,
                widgetIndex: 0,
            };
            const preferredPosition = widgetDef.defaultFloatingPosition;
            if (floatingContainerId in state.widgets) {
                state = (0, appui_layout_react_1.addTabToWidget)(state, widgetDef.id, floatingContainerId);
            }
            else {
                const tab = state.tabs[widgetDef.id];
                const size = {
                    height: 200,
                    width: 300,
                    ...tab.preferredFloatingWidgetSize,
                };
                const preferredPoint = preferredPosition ?? {
                    x: (state.size.width - size.width) / 2,
                    y: (state.size.height - size.height) / 2,
                };
                const nzBounds = core_react_1.Rectangle.createFromSize(state.size);
                const bounds = core_react_1.Rectangle.createFromSize(size).offset(preferredPoint);
                const containedBounds = bounds.containIn(nzBounds);
                state = (0, appui_layout_react_1.addFloatingWidget)(state, floatingContainerId, [widgetDef.id], {
                    bounds: containedBounds.toProps(),
                    home,
                    userSized,
                });
            }
        }
        else {
            const preferredWidgetIndex = section;
            const widgetPanelSectionId = (0, appui_layout_react_1.getWidgetPanelSectionId)(side, preferredWidgetIndex);
            if (widgetPanelSectionId in state.widgets) {
                state = (0, appui_layout_react_1.addTabToWidget)(state, widgetDef.id, widgetPanelSectionId);
            }
            else {
                const panel = state.panels[side];
                if (panel.widgets.length < panel.maxWidgetCount) {
                    state = (0, appui_layout_react_1.addPanelWidget)(state, side, widgetPanelSectionId, [
                        widgetDef.id,
                    ]);
                }
                else {
                    const widgetIndex = Math.min(preferredWidgetIndex, panel.widgets.length - 1);
                    const widgetId = panel.widgets[widgetIndex];
                    state = (0, appui_layout_react_1.addTabToWidget)(state, widgetDef.id, widgetId);
                }
            }
        }
        if (widgetDef.defaultState === WidgetState_1.WidgetState.Hidden) {
            state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
                type: "WIDGET_TAB_HIDE",
                id: widgetDef.id,
            });
        }
    }
    return state;
}
exports.appendWidgets = appendWidgets;
function processPopoutWidgets(state) {
    // Electron reopens popout windows
    if (core_bentley_1.ProcessDetector.isElectronAppFrontend) {
        return state;
    }
    for (const popoutWidgetId of state.popoutWidgets.allIds) {
        const widget = state.widgets[popoutWidgetId];
        const id = widget.tabs[0];
        state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
            type: "WIDGET_TAB_FLOAT",
            id,
        });
    }
    return state;
}
/** Adds frontstageDef widgets that are missing in NineZoneState.
 * @internal
 */
function addMissingWidgets(frontstageDef, initialState) {
    let state = initialState;
    state = appendWidgets(state, determineNewWidgets(frontstageDef.leftPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.Start)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Left, StagePanelSection_1.StagePanelSection.Start);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.leftPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.End)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Left, StagePanelSection_1.StagePanelSection.End);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.rightPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.Start)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Right, StagePanelSection_1.StagePanelSection.Start);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.rightPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.End)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Right, StagePanelSection_1.StagePanelSection.End);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.topPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.Start)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Top, StagePanelSection_1.StagePanelSection.Start);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.topPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.End)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Top, StagePanelSection_1.StagePanelSection.End);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.bottomPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.Start)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Bottom, StagePanelSection_1.StagePanelSection.Start);
    state = appendWidgets(state, determineNewWidgets(frontstageDef.bottomPanel?.getPanelSectionDef(StagePanelSection_1.StagePanelSection.End)
        .widgetDefs, state), StagePanelLocation_1.StagePanelLocation.Bottom, StagePanelSection_1.StagePanelSection.End);
    if (frontstageDef.toolSettings) {
        const newToolSettingsWidgets = determineNewWidgets([frontstageDef.toolSettings], state);
        for (const newToolSettingsWidget of newToolSettingsWidgets) {
            state = (0, appui_layout_react_1.addTab)(state, newToolSettingsWidget.id, toTabArgs(newToolSettingsWidget));
        }
    }
    return state;
}
exports.addMissingWidgets = addMissingWidgets;
/** Hide widgets with Hidden defaultState. */
function hideWidgets(state, frontstageDef) {
    const tabs = Object.values(state.tabs);
    for (const tab of tabs) {
        const widgetDef = frontstageDef.findWidgetDef(tab.id);
        if (!widgetDef)
            continue;
        if (widgetDef.defaultState === WidgetState_1.WidgetState.Hidden) {
            state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
                type: "WIDGET_TAB_HIDE",
                id: widgetDef.id,
            });
        }
    }
    return state;
}
/** Removes NineZoneState widgets that are missing in frontstageDef.
 * @internal
 */
function removeMissingWidgets(frontstageDef, state) {
    const toolSettingsTabId = state.toolSettings?.tabId;
    for (const [, tab] of Object.entries(state.tabs)) {
        if (tab.id === toolSettingsTabId)
            continue;
        const widgetDef = frontstageDef.findWidgetDef(tab.id);
        if (widgetDef)
            continue;
        state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
            type: "WIDGET_TAB_HIDE",
            id: tab.id,
        });
        state = (0, appui_layout_react_1.removeTab)(state, tab.id);
    }
    return state;
}
function getWidgetLabel(label) {
    return label === "" ? "Widget" : label;
}
/** @internal */
function getWidgetId(location, section) {
    switch (location) {
        case StagePanelLocation_1.StagePanelLocation.Left: {
            if (section === StagePanelSection_1.StagePanelSection.Start)
                return "leftStart";
            return "leftEnd";
        }
        case StagePanelLocation_1.StagePanelLocation.Right: {
            if (section === StagePanelSection_1.StagePanelSection.Start)
                return "rightStart";
            return "rightEnd";
        }
        case StagePanelLocation_1.StagePanelLocation.Top: {
            if (section === StagePanelSection_1.StagePanelSection.Start)
                return "topStart";
            return "topEnd";
        }
        case StagePanelLocation_1.StagePanelLocation.Bottom: {
            if (section === StagePanelSection_1.StagePanelSection.Start)
                return "bottomStart";
            return "bottomEnd";
        }
    }
}
exports.getWidgetId = getWidgetId;
/** @internal */
function getPanelSectionWidgets(frontstageDef, location, section) {
    const stagePanel = frontstageDef.getStagePanelDef(location);
    const panelSection = stagePanel?.getPanelSectionDef(section);
    return panelSection?.widgetDefs || [];
}
exports.getPanelSectionWidgets = getPanelSectionWidgets;
/** @internal */
function addPanelWidgets(state, frontstageDef, location) {
    const side = (0, StagePanelDef_1.toPanelSide)(location);
    const start = getWidgetId(location, StagePanelSection_1.StagePanelSection.Start);
    const startWidgets = getPanelSectionWidgets(frontstageDef, location, StagePanelSection_1.StagePanelSection.Start);
    state = addWidgets(state, determineNewWidgets(startWidgets, state), side, start);
    const end = getWidgetId(location, StagePanelSection_1.StagePanelSection.End);
    const endWidgets = getPanelSectionWidgets(frontstageDef, location, StagePanelSection_1.StagePanelSection.End);
    state = addWidgets(state, determineNewWidgets(endWidgets, state), side, end);
    return state;
}
exports.addPanelWidgets = addPanelWidgets;
/** @internal */
function isFrontstageStateSettingResult(settingsResult) {
    if (settingsResult.status === core_react_1.UiStateStorageStatus.Success)
        return true;
    return false;
}
exports.isFrontstageStateSettingResult = isFrontstageStateSettingResult;
/** @internal */
function initializePanel(state, frontstageDef, location) {
    const side = (0, StagePanelDef_1.toPanelSide)(location);
    state = addPanelWidgets(state, frontstageDef, location);
    const panelDef = frontstageDef.getStagePanelDef(location);
    state = (0, immer_1.default)(state, (draft) => {
        const panel = draft.panels[side];
        panel.minSize = panelDef?.initialConfig?.minSize ?? panel.minSize;
        panel.pinned = panelDef?.pinned ?? panel.pinned;
        panel.resizable = panelDef?.resizable ?? panel.resizable;
        panel.maxSize = panelDef?.initialConfig?.maxSize ?? panel.maxSize;
    });
    if (panelDef?.size !== undefined) {
        state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
            type: "PANEL_SET_SIZE",
            side,
            size: panelDef.size,
        });
    }
    return state;
}
exports.initializePanel = initializePanel;
/** @internal */
exports.stateVersion = 16; // this needs to be bumped when NineZoneState is changed (to recreate the layout).
/** @internal */
function initializeNineZoneState(frontstageDef) {
    let nineZone = defaultNineZone;
    nineZone = (0, immer_1.default)(nineZone, (stateDraft) => {
        // istanbul ignore next
        if (!InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize)
            return;
        stateDraft.size = {
            height: InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.height,
            width: InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.width,
        };
    });
    nineZone = initializePanel(nineZone, frontstageDef, StagePanelLocation_1.StagePanelLocation.Left);
    nineZone = initializePanel(nineZone, frontstageDef, StagePanelLocation_1.StagePanelLocation.Right);
    nineZone = initializePanel(nineZone, frontstageDef, StagePanelLocation_1.StagePanelLocation.Top);
    nineZone = initializePanel(nineZone, frontstageDef, StagePanelLocation_1.StagePanelLocation.Bottom);
    nineZone = (0, immer_1.default)(nineZone, (draft) => {
        for (const [, panel] of Object.entries(draft.panels)) {
            const expanded = panel.widgets.find((widgetId) => draft.widgets[widgetId].minimized === false);
            const firstWidget = panel.widgets.length > 0 ? draft.widgets[panel.widgets[0]] : undefined;
            // istanbul ignore next
            if (!expanded && firstWidget) {
                firstWidget.minimized = false;
            }
        }
        draft.panels.left.collapsed = isPanelCollapsed(frontstageDef.leftPanel?.panelState);
        draft.panels.right.collapsed = isPanelCollapsed(frontstageDef.rightPanel?.panelState);
        draft.panels.top.collapsed = isPanelCollapsed(frontstageDef.topPanel?.panelState);
        draft.panels.bottom.collapsed = isPanelCollapsed(frontstageDef.bottomPanel?.panelState);
    });
    nineZone = addMissingWidgets(frontstageDef, nineZone);
    const toolSettingsWidgetDef = frontstageDef.toolSettings;
    if (toolSettingsWidgetDef) {
        const toolSettingsTabId = toolSettingsWidgetDef.id;
        nineZone = (0, appui_layout_react_1.addDockedToolSettings)(nineZone, toolSettingsTabId);
    }
    nineZone = hideWidgets(nineZone, frontstageDef);
    nineZone = processPopoutWidgets(nineZone);
    return nineZone;
}
exports.initializeNineZoneState = initializeNineZoneState;
/** Converts from saved NineZoneState to NineZoneState.
 * @note Restores toolSettings tab.
 * @note Restores tab labels.
 * @internal
 */
function restoreNineZoneState(frontstageDef, saved) {
    let state = {
        ...saved,
        tabs: {},
    };
    for (const [, tab] of Object.entries(saved.tabs)) {
        // Re-add the placeholder tab in order to correctly remove it from the state if WidgetDef is not found.
        state = (0, appui_layout_react_1.addTab)(state, tab.id);
        const widgetDef = frontstageDef.findWidgetDef(tab.id);
        if (!widgetDef) {
            core_bentley_1.Logger.logInfo(UiFramework_1.UiFramework.loggerCategory(restoreNineZoneState), "WidgetDef is not found for saved tab.", () => ({
                frontstageId: frontstageDef.id,
                tabId: tab.id,
            }));
            state = (0, appui_layout_react_1.removeTab)(state, tab.id);
            continue;
        }
        state = (0, immer_1.default)(state, (draft) => {
            draft.tabs[tab.id] = {
                ...tab,
                ...toTabArgs(widgetDef),
                preferredFloatingWidgetSize: tab.preferredFloatingWidgetSize,
                preferredPanelWidgetSize: tab.preferredPanelWidgetSize,
            };
        });
    }
    state = (0, immer_1.default)(state, (draft) => {
        // remove center panel section if one is found in left or right panels
        const oldLeftMiddleIndex = saved.panels.left.widgets.findIndex((value) => value === "leftMiddle");
        // istanbul ignore next
        if (-1 !== oldLeftMiddleIndex) {
            draft.panels.left.widgets = saved.panels.left.widgets.filter((value) => value !== "leftMiddle");
            if ("leftEnd" in draft.widgets) {
                draft.widgets.leftMiddle.tabs.forEach((tab) => draft.widgets.leftEnd.tabs.push(tab));
            }
            else {
                draft.widgets.leftEnd = { ...draft.widgets.leftMiddle };
                delete draft.widgets.leftMiddle;
            }
        }
        const oldRightMiddleIndex = saved.panels.right.widgets.findIndex((value) => value === "rightMiddle");
        // istanbul ignore next
        if (-1 !== oldRightMiddleIndex) {
            draft.panels.right.widgets = saved.panels.right.widgets.filter((value) => value !== "rightMiddle");
            if ("rightEnd" in draft.widgets) {
                draft.widgets.rightMiddle.tabs.forEach((tab) => draft.widgets.rightEnd.tabs.push(tab));
            }
            else {
                draft.widgets.rightEnd = { ...draft.widgets.rightMiddle };
                delete draft.widgets.rightMiddle;
            }
        }
        return;
    });
    if (InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize &&
        (0 !== InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.height ||
            0 !== InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.width)) {
        state = (0, appui_layout_react_1.NineZoneStateReducer)(state, {
            type: "RESIZE",
            size: {
                height: InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.height,
                width: InternalFrontstageManager_1.InternalFrontstageManager.nineZoneSize.width,
            },
        });
    }
    state = addMissingWidgets(frontstageDef, state);
    state = hideWidgets(state, frontstageDef);
    state = processPopoutWidgets(state);
    return state;
}
exports.restoreNineZoneState = restoreNineZoneState;
/** Prepares NineZoneState to be saved.
 * @note Removes toolSettings tab.
 * @note Removes tab labels and iconSpec.
 * @internal
 */
function packNineZoneState(state) {
    let packed = {
        ...state,
        tabs: {},
    };
    packed = (0, immer_1.default)(packed, (draft) => {
        for (const [, tab] of Object.entries(state.tabs)) {
            draft.tabs[tab.id] = {
                id: tab.id,
                preferredFloatingWidgetSize: tab.preferredFloatingWidgetSize,
                userSized: tab.userSized,
            };
        }
    });
    return packed;
}
exports.packNineZoneState = packNineZoneState;
/** @internal */
function isPanelCollapsed(panelState) {
    return panelState !== StagePanelDef_1.StagePanelState.Open;
}
exports.isPanelCollapsed = isPanelCollapsed;
/** @internal */
function showWidget(state, id) {
    const location = (0, appui_layout_react_1.getTabLocation)(state, id);
    if (!location)
        return state;
    state = (0, immer_1.default)(state, (draft) => {
        const widget = draft.widgets[location.widgetId];
        widget.activeTabId = id;
        widget.minimized = false;
        if ((0, appui_layout_react_1.isPanelTabLocation)(location)) {
            const panel = draft.panels[location.side];
            panel.collapsed = false;
        }
    });
    if ((0, appui_layout_react_1.isFloatingTabLocation)(location)) {
        state = (0, appui_layout_react_1.floatingWidgetBringToFront)(state, location.floatingWidgetId);
    }
    return state;
}
exports.showWidget = showWidget;
/** @internal */
function expandWidget(state, id) {
    const location = (0, appui_layout_react_1.getTabLocation)(state, id);
    if (!location)
        return state;
    return (0, immer_1.default)(state, (draft) => {
        const widget = draft.widgets[location.widgetId];
        if ((0, appui_layout_react_1.isPanelTabLocation)(location)) {
            const panel = draft.panels[location.side];
            panel.splitterPercent =
                panel.widgets.findIndex((wId) => wId === location.widgetId) === 0
                    ? 100
                    : 0;
        }
        widget.minimized = false;
    });
}
exports.expandWidget = expandWidget;
/** @internal */
function useSavedFrontstageState(frontstageDef) {
    const uiStateStorage = (0, useUiStateStorage_1.useUiStateStorageHandler)();
    const uiStateStorageRef = React.useRef(uiStateStorage);
    const isMountedRef = React.useRef(false);
    React.useEffect(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false;
        };
    }, []);
    React.useEffect(() => {
        uiStateStorageRef.current = uiStateStorage;
    }, [uiStateStorage]);
    React.useEffect(() => {
        async function fetchFrontstageState() {
            if (frontstageDef.nineZoneState) {
                frontstageDef.nineZoneState = processPopoutWidgets(frontstageDef.nineZoneState);
                return;
            }
            const id = frontstageDef.id;
            const version = frontstageDef.version;
            const settingResult = await uiStateStorageRef.current.getSetting(exports.FRONTSTAGE_SETTINGS_NAMESPACE, getFrontstageStateSettingName(id));
            if (!isMountedRef.current)
                return;
            if (isFrontstageStateSettingResult(settingResult)) {
                const setting = settingResult.setting;
                if (setting.version === version &&
                    setting.stateVersion === exports.stateVersion) {
                    frontstageDef.nineZoneState = restoreNineZoneState(frontstageDef, setting.nineZone);
                    return;
                }
            }
            frontstageDef.nineZoneState = initializeNineZoneState(frontstageDef);
        }
        void fetchFrontstageState();
    }, [frontstageDef]);
}
exports.useSavedFrontstageState = useSavedFrontstageState;
/** @internal */
function useSaveFrontstageSettings(frontstageDef, store) {
    const uiSettingsStorage = (0, useUiStateStorage_1.useUiStateStorageHandler)();
    const saveSetting = React.useMemo(() => {
        const debounced = debounce(async (frontstage, state) => {
            const id = frontstage.id;
            const setting = {
                id,
                version: frontstage.version,
                stateVersion: exports.stateVersion,
                nineZone: packNineZoneState(state),
            };
            await uiSettingsStorage.saveSetting(exports.FRONTSTAGE_SETTINGS_NAMESPACE, getFrontstageStateSettingName(id), setting);
        }, 1000);
        const save = (frontstage, state) => {
            if (state.draggedTab)
                return;
            debounced(frontstage, state);
        };
        save.cancel = debounced.cancel;
        return save;
    }, [uiSettingsStorage]);
    React.useEffect(() => {
        return () => {
            saveSetting.cancel();
        };
    }, [saveSetting]);
    React.useEffect(() => {
        saveSetting(frontstageDef, store.getState());
    }, [saveSetting, frontstageDef, store]);
    React.useEffect(() => {
        return store.subscribe(() => {
            saveSetting(frontstageDef, store.getState());
        });
    }, [saveSetting, frontstageDef, store]);
}
exports.useSaveFrontstageSettings = useSaveFrontstageSettings;
/** @internal */
exports.FRONTSTAGE_SETTINGS_NAMESPACE = "uifw-frontstageSettings";
/** @internal */
function getFrontstageStateSettingName(frontstageId) {
    return `frontstageState[${frontstageId}]`;
}
exports.getFrontstageStateSettingName = getFrontstageStateSettingName;
// istanbul ignore next
function debounce(func, duration) {
    let timeout;
    const debounced = (...args) => {
        const handler = () => {
            timeout = undefined;
            return func(...args);
        };
        window.clearTimeout(timeout);
        timeout = window.setTimeout(handler, duration);
    };
    debounced.cancel = () => {
        window.clearTimeout(timeout);
    };
    return debounced;
}
/** @internal */
function useFrontstageManager(frontstageDef, useToolAsToolSettingsLabel) {
    const uiSettingsStorage = (0, useUiStateStorage_1.useUiStateStorageHandler)();
    React.useEffect(() => {
        return InternalFrontstageManager_1.InternalFrontstageManager.onFrontstageRestoreLayoutEvent.addListener((args) => {
            // TODO: track restoring frontstages to support workflows:  i.e. prevent loading frontstage OR saving layout when delete is pending
            void uiSettingsStorage.deleteSetting(exports.FRONTSTAGE_SETTINGS_NAMESPACE, getFrontstageStateSettingName(args.frontstageDef.id));
            if (frontstageDef.id === args.frontstageDef.id) {
                args.frontstageDef.nineZoneState =
                    initializeNineZoneState(frontstageDef);
            }
            else {
                args.frontstageDef.nineZoneState = undefined;
            }
        });
    }, [uiSettingsStorage, frontstageDef]);
    const defaultLabel = React.useMemo(() => UiFramework_1.UiFramework.translate("widget.labels.toolSettings"), []);
    React.useEffect(() => {
        const updateLabel = () => {
            const state = frontstageDef.nineZoneState;
            if (!state)
                return;
            const toolSettingsTabId = state.toolSettings?.tabId;
            if (!toolSettingsTabId)
                return;
            const toolId = UiFramework_1.UiFramework.frontstages.activeToolId;
            const label = useToolAsToolSettingsLabel
                ? core_frontend_1.IModelApp.tools.find(toolId)?.flyover || defaultLabel
                : defaultLabel;
            frontstageDef.dispatch({
                type: "WIDGET_TAB_SET_LABEL",
                id: toolSettingsTabId,
                label,
            });
        };
        // Whenever the frontstageDef or the useTool... changes, keep the label up to date.
        updateLabel();
        const removeListenerFuncs = [];
        // If useTool... is true, listen for events to keep up the label up to date.
        if (useToolAsToolSettingsLabel) {
            removeListenerFuncs.push(UiFramework_1.UiFramework.frontstages.onFrontstageReadyEvent.addListener(updateLabel), InternalFrontstageManager_1.InternalFrontstageManager.onFrontstageRestoreLayoutEvent.addListener(updateLabel), UiFramework_1.UiFramework.frontstages.onToolActivatedEvent.addListener(updateLabel), UiFramework_1.UiFramework.frontstages.onToolSettingsReloadEvent.addListener(updateLabel));
        }
        return () => {
            removeListenerFuncs.forEach((removeListener) => removeListener());
        };
    }, [frontstageDef, useToolAsToolSettingsLabel, defaultLabel]);
}
exports.useFrontstageManager = useFrontstageManager;
/** @internal */
// istanbul ignore next
function useItemsManager(frontstageDef) {
    const refreshNineZoneState = (def) => {
        // Fired for both registered/unregistered. Update definitions and remove/add missing widgets.
        def.updateWidgetDefs();
        let state = def.nineZoneState;
        if (!state)
            return;
        state = addMissingWidgets(def, state);
        state = removeMissingWidgets(def, state);
        def.nineZoneState = state;
    };
    React.useEffect(() => {
        // Need to refresh anytime frontstageDef changes because uiItemsProvider may have added something to
        // another stage before it was possibly unloaded in this stage.
        refreshNineZoneState(frontstageDef);
    }, [frontstageDef]);
    React.useEffect(() => {
        return UiItemsManager_1.UiItemsManager.onUiProviderRegisteredEvent.addListener(() => {
            refreshNineZoneState(frontstageDef);
        });
    }, [frontstageDef]);
}
exports.useItemsManager = useItemsManager;
// istanbul ignore next
function determineNewWidgets(defs, state) {
    defs = defs || [];
    const uniqueDefs = defs.filter((def, index, array) => {
        return index === array.findIndex((def1) => def.id === def1.id);
    });
    return uniqueDefs.filter((def) => !(def.id in state.tabs));
}
//# sourceMappingURL=Frontstage.js.map