/*---------------------------------------------------------------------------------------------
 * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
 * See LICENSE.md in the project root for license terms and full copyright notice.
 *--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Utilities
 */
import * as React from "react";
import { useSyncExternalStore } from "use-sync-external-store/shim";
import { SyncUiEventDispatcher } from "../syncui/SyncUiEventDispatcher";
/** Duck type the conditional. */
function isConditionalValue(conditionalProp) {
    return (typeof conditionalProp === "object" &&
        conditionalProp &&
        "syncEventIds" in conditionalProp &&
        "refresh" in conditionalProp &&
        "value" in conditionalProp);
}
/** @internal */
export function useConditionalProp(conditionalProp) {
    const subscribe = React.useCallback((onStoreChange) => {
        if (isConditionalValue(conditionalProp)) {
            return SyncUiEventDispatcher.onSyncUiEvent.addListener(({ eventIds }) => {
                if (!conditionalProp.syncEventIds.some((id) => eventIds.has(id)))
                    return;
                if (!conditionalProp.refresh())
                    return;
                onStoreChange();
            });
        }
        return () => { };
    }, [conditionalProp]);
    const getSnapshot = React.useCallback(() => {
        if (isConditionalValue(conditionalProp))
            return conditionalProp.value;
        return conditionalProp;
    }, [conditionalProp]);
    return useSyncExternalStore(subscribe, getSnapshot);
}
//# sourceMappingURL=useConditionalProp.js.map