UNPKG

@carbon/react

Version:

React components for the Carbon Design System

49 lines (41 loc) 1.52 kB
/** * 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. */ 'use strict'; var React = require('react'); var usePresence = require('./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 = React.useRef(initialPresenceId); const presenceRef = React.useRef(null); const prevPresenceRef = React.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.usePresence(presenceRef, open); const isPresenceExclusive = React.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 = React.useMemo(() => ({ presenceRef, isPresenceExclusive, isExiting }), [presenceRef, isPresenceExclusive, isExiting]); return [isPresent, contextValue]; }; exports.usePresenceContext = usePresenceContext;