UNPKG

@mskcc/carbon-react

Version:

Carbon react components for the MSKCC DSM

62 lines (56 loc) 1.69 kB
/** * MSKCC 2021, 2024 */ import { useLayoutEffect, useEffect, useState, useId as useId$1 } from 'react'; import setupGetInstanceId from '../tools/setupGetInstanceId.js'; import { canUseDOM } from './environment.js'; import { useIdPrefix } from './useIdPrefix.js'; // This file was heavily inspired by Reach UI and their work on their auto-id const getId = setupGetInstanceId(); const useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect; let serverHandoffCompleted = false; /** * Generate a unique ID with an optional prefix prepended to it * @param {string} [prefix] * @returns {string} */ function useId() { let prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'id'; const _prefix = useIdPrefix(); const [id, setId] = useState(() => { if (serverHandoffCompleted) { return `${_prefix ? `${_prefix}-` : ``}${prefix}-${getId()}`; } return null; }); useIsomorphicLayoutEffect(() => { if (id === null) { setId(`${_prefix ? `${_prefix}-` : ``}${prefix}-${getId()}`); } }, [getId]); useEffect(() => { if (serverHandoffCompleted === false) { serverHandoffCompleted = true; } }, []); if (useId$1) { const id = nativeReactUseId(_prefix, prefix); return id; } return id; } function nativeReactUseId(_prefix, prefix) { const getId = useId$1(); const id = `${_prefix ? `${_prefix}-` : ``}${prefix}-${getId}`; return id; } /** * Generate a unique id if a given `id` is not provided * @param {string|number|undefined} id * @returns {string} */ function useFallbackId(id) { const fallback = useId(); return id ?? fallback; } export { useFallbackId, useId };