/*---------------------------------------------------------------------------------------------
 * 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
 */
import { castDraft, produce } from "immer";
import * as React from "react";
import { create } from "zustand";
import { BeEvent } from "@itwin/core-bentley";
/** @internal */
export function WidgetContentManager(props) {
    const setContentContainer = useContainersStore((state) => state.setContainer);
    const saveTransientStateRef = React.useRef(new BeEvent());
    const restoreTransientStateRef = React.useRef(new BeEvent());
    const setContainer = React.useCallback((tabId, container) => {
        if (!container) {
            saveTransientStateRef.current.raiseEvent(tabId);
        }
        setContentContainer(tabId, container);
    }, [setContentContainer]);
    const widgetContentManagerContextValue = React.useMemo(() => ({
        setContainer,
        onSaveTransientState: saveTransientStateRef.current,
        onRestoreTransientState: restoreTransientStateRef.current,
    }), [setContainer]);
    return (React.createElement(WidgetContentManagerContext.Provider, { value: widgetContentManagerContextValue }, props.children));
}
/** @internal */
export const useContainersStore = create((set) => ({
    containers: {},
    setContainer: (tabId, container) => {
        set((state) => produce(state, (draft) => {
            if (!container) {
                delete draft.containers[tabId];
                return;
            }
            draft.containers[tabId] = castDraft(container);
        }));
    },
}));
/** @internal */
export const WidgetContentManagerContext = React.createContext(undefined);
WidgetContentManagerContext.displayName = "nz:WidgetContentManagerContext";
//# sourceMappingURL=ContentManager.js.map