import React, { FC, useEffect, useRef, useState, } from 'react'; import { overflowsY, focusableSelector } from '@aarhus-university/au-designsystem-delphinus/source/js/components/helpers'; import { truncate } from '@aarhus-university/au-designsystem-delphinus/source/js/components/truncator'; const getMaxLinesStyle = (maxLines: number): React.CSSProperties => ({ '--max-lines': maxLines } as React.CSSProperties); type Props = { maxLines: number; header?: string; headerLevel?: number; children: string | React.JSX.Element | React.JSX.Element[]; classNames?: string; buttonChild: React.JSX.Element; }; let lastWidth = window.innerWidth; let resizeTimeout: ReturnType; let onResize: () => void; let onFocus: (event: Event) => void; const AUTruncatorComponent: FC = ({ maxLines, header = undefined, headerLevel = 2, children, classNames = 'truncator', buttonChild, }) => { const expandRef = useRef(null); const contentRef = useRef(null); const [expanded, setExpanded] = useState(false); useEffect(() => { window.removeEventListener('resize', onResize); if (expanded) { (expandRef.current as HTMLElement).removeAttribute('hidden'); expandRef.current?.parentElement?.classList.add('truncator--no-truncation'); } truncate(expandRef.current as HTMLElement, contentRef.current as HTMLElement); onResize = () => { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { if (window.innerWidth !== lastWidth) { expandRef.current?.setAttribute('hidden', 'hidden'); expandRef.current?.parentElement?.classList.remove('truncator--no-truncation'); lastWidth = window.innerWidth; setExpanded(false); } }, 200); }; window.addEventListener('resize', onResize); const focusElements = contentRef.current?.querySelectorAll(focusableSelector); onFocus = (event: Event) => { if (overflowsY(event.target as HTMLElement)) { setExpanded(true); } }; if (focusElements) { focusElements.forEach((f) => { f.removeEventListener('focus', onFocus); f.addEventListener('focus', onFocus); }); } return () => { if (focusElements) { focusElements.forEach((f) => { f.removeEventListener('focus', onFocus); }); } window.removeEventListener('resize', onResize); }; }, [expanded]); return (
{ header && ( <> { headerLevel === 1 && (

{header}

) } { headerLevel === 2 && (

{header}

) } { headerLevel === 3 && (

{header}

) } { headerLevel === 4 && (

{header}

) } { headerLevel === 5 && (
{header}
) } { headerLevel === 6 && (
{header}
) } ) }
{children}
); }; AUTruncatorComponent.displayName = 'AUTruncatorComponent'; export default AUTruncatorComponent;