Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | 83x 83x 83x 83x 83x 83x 83x 83x 73x 73x 73x 73x 73x 73x 73x 73x 83x 3x | import {useLayoutEffect, useRef, useState} from "react"; import {useTranslation} from "react-i18next"; import clsx from "clsx"; import {ChevronDown, ChevronUp} from "lucide-react"; export function ExpandableText({value = "", maxLines = 3, className = ""}) { const [expanded, setExpanded] = useState(false); const [showButton, setShowButton] = useState(false); const [contentHeight, setContentHeight] = useState(0); const paragraphRef = useRef(null); const {t} = useTranslation(); const lineHeightEm = 1.5; // 1.5em is the normal average const collapsedHeightEm = maxLines * lineHeightEm; useLayoutEffect(() => { const el = paragraphRef.current; Iif (!el) return; const scrollHeight = el.scrollHeight; setContentHeight(scrollHeight); const fontSize = parseFloat(getComputedStyle(el).fontSize); const collapsedHeightEm = maxLines * 1.5; const collapsedHeightPx = collapsedHeightEm * fontSize; setShowButton(scrollHeight > collapsedHeightPx); }, [value, maxLines]); return ( <div className="relative"> <div ref={paragraphRef} className={clsx( "text-sm sm:text-base whitespace-pre-line overflow-hidden transition-[max-height] duration-500 ease-in-out relative", className )} style={{ maxHeight: expanded ? `${contentHeight}px` : `${collapsedHeightEm}em`, }} aria-expanded={expanded} > {value} {!expanded && showButton && ( <div className="absolute bottom-0 left-0 w-full h-6 bg-gradient-to-t from-white dark:from-slate-900 pointer-events-none"/> )} </div> {showButton && ( <div className="mt-1 flex justify-end"> <button onClick={() => setExpanded(!expanded)} className="text-xs text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1" type="button" > {expanded ? ( <> {t("showLess")} <ChevronUp className="w-4 h-4"/> </> ) : ( <> {t("showMore")} <ChevronDown className="w-4 h-4"/> </> )} </button> </div> )} </div> ); } |