UNPKG

@carbon/react

Version:

React components for the Carbon Design System

79 lines (77 loc) 2.5 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 useIsomorphicEffect from "../../internal/useIsomorphicEffect.js"; import classNames from "classnames"; import { useRef } from "react"; import PropTypes from "prop-types"; import { Fragment, jsx } from "react/jsx-runtime"; //#region src/components/SkeletonText/SkeletonText.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. */ const randoms = [ .973051493507435, .15334737213558558, .5671034553053769 ]; function getRandomInt(min, max, n) { return Math.floor(randoms[n % 3] * (max - min + 1)) + min; } const SkeletonText = ({ paragraph = false, lineCount = 3, width = "100%", heading = false, className = "", ...rest }) => { const prefix = usePrefix(); const skeletonTextClasses = classNames({ [`${prefix}--skeleton__text`]: true, [`${prefix}--skeleton__heading`]: heading, [className]: className }); const widthNum = parseInt(width, 10); const widthPx = width.includes("px"); const widthPercent = width.includes("%"); let lineCountNumber = 1; if (paragraph) lineCountNumber = lineCount; const refs = useRef([]); useIsomorphicEffect(() => { refs.current.map((item, j) => { const randomPercentWidth = getRandomInt(0, 75, j) + "px"; const randomPxWidth = getRandomInt(Math.max(widthNum - 75, 0), widthNum, j) + "px"; if (item) if (widthPercent && paragraph) item.style.width = `calc(${width} - ${randomPercentWidth})`; else if (widthPx && paragraph) item.style.width = randomPxWidth; else item.style.width = width; }); }, [ lineCountNumber, paragraph, refs, width, widthNum, widthPercent, widthPx ]); const lines = []; for (let i = 0; i < lineCountNumber; i++) lines.push(/* @__PURE__ */ jsx("p", { className: skeletonTextClasses, ref: (el) => { refs.current = [...refs.current, el]; }, ...rest }, i)); if (lineCountNumber !== 1) return /* @__PURE__ */ jsx("div", { children: lines }); return /* @__PURE__ */ jsx(Fragment, { children: lines }); }; SkeletonText.propTypes = { className: PropTypes.string, heading: PropTypes.bool, lineCount: PropTypes.number, paragraph: PropTypes.bool, width: PropTypes.string }; //#endregion export { SkeletonText as default };