UNPKG

@carbon/react

Version:

React components for the Carbon Design System

80 lines (78 loc) 2.75 kB
/** * Copyright IBM Corp. 2016, 2026 * * 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 { usePrefix } from "../../internal/usePrefix.js"; import { useMergedRefs } from "../../internal/useMergedRefs.js"; import classNames from "classnames"; import { forwardRef, useEffect, useRef, useState } from "react"; import PropTypes from "prop-types"; import { jsx } from "react/jsx-runtime"; //#region src/components/ListBox/ListBoxMenuItem.tsx /** * Copyright IBM Corp. 2016, 2026 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /** * Determines if the content of an element is truncated. * * Merges a forwarded ref with a local ref to check the element's dimensions. * * @template T * @param forwardedRef - A ref passed from the parent component. * @param deps - Dependencies to re-run the truncation check. * @returns An object containing the truncation state and the merged ref. */ const useIsTruncated = (forwardedRef, deps = []) => { const localRef = useRef(null); const mergedRef = useMergedRefs([...forwardedRef ? [forwardedRef] : [], localRef]); const [isTruncated, setIsTruncated] = useState(false); useEffect(() => { const element = localRef.current; if (element) { const { offsetWidth, scrollWidth } = element; setIsTruncated(offsetWidth < scrollWidth); } }, [localRef, ...deps]); return { isTruncated, ref: mergedRef }; }; /** * `ListBoxMenuItem` is a helper component for managing the container class * name, alongside any classes for any corresponding states, for a generic list * box menu item. */ const ListBoxMenuItem = forwardRef(({ children, isActive = false, isHighlighted = false, title, ...rest }, forwardedRef) => { const prefix = usePrefix(); const { isTruncated, ref: menuItemOptionRef } = useIsTruncated(forwardedRef && typeof forwardedRef !== "function" ? forwardedRef.menuItemOptionRef : void 0, [children]); const className = classNames(`${prefix}--list-box__menu-item`, { [`${prefix}--list-box__menu-item--active`]: isActive, [`${prefix}--list-box__menu-item--highlighted`]: isHighlighted }); return /* @__PURE__ */ jsx("li", { ...rest, className, title: isTruncated ? title : void 0, children: /* @__PURE__ */ jsx("div", { className: `${prefix}--list-box__menu-item__option`, ref: menuItemOptionRef, children }) }); }); ListBoxMenuItem.displayName = "ListBoxMenuItem"; ListBoxMenuItem.propTypes = { children: PropTypes.node, disabled: PropTypes.bool, isActive: PropTypes.bool, isHighlighted: PropTypes.bool, title: PropTypes.string }; //#endregion export { ListBoxMenuItem as default };