@carbon/react
Version:
React components for the Carbon Design System
47 lines (40 loc) • 1.48 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useRef, useCallback, useMemo } from 'react';
import { usePresence } from './usePresence.js';
/**
* Returns if the presence node is present and the context value to be used by a presence context, e.g. ModalPresence.
*/
const usePresenceContext = (open, initialPresenceId) => {
const presenceIdRef = useRef(initialPresenceId);
const presenceRef = useRef(null);
const prevPresenceRef = useRef(null);
// clean up the presence id, if not predefined and if the presence node was unmounted
if (!initialPresenceId && prevPresenceRef.current && !presenceRef.current) {
presenceIdRef.current = null;
}
prevPresenceRef.current = presenceRef.current;
const {
isPresent,
isExiting
} = usePresence(presenceRef, open);
const isPresenceExclusive = useCallback(id => {
if (!id) return false;
// return false if the presence context is occupied
if (presenceIdRef.current && presenceIdRef.current !== id) return false;
// otherwise occupy presence context and return true
presenceIdRef.current = id;
return true;
}, []);
const contextValue = useMemo(() => ({
presenceRef,
isPresenceExclusive,
isExiting
}), [presenceRef, isPresenceExclusive, isExiting]);
return [isPresent, contextValue];
};
export { usePresenceContext };