| 1 |
import { Fragment, useEffect, useRef, useState, forwardRef, useImperativeHandle } from 'react'; |
| 2 |
import styles from '@patternfly/react-styles/css/components/Truncate/truncate'; |
| 3 |
import { css } from '@patternfly/react-styles'; |
| 4 |
import { Tooltip, TooltipPosition, TooltipProps } from '../Tooltip'; |
| 5 |
import { getReferenceElement } from '../../helpers'; |
| 6 |
import { getResizeObserver } from '../../helpers/resizeObserver'; |
| 7 |
import { debounce } from '../../helpers/util'; |
| 8 |
|
| 9 |
export enum TruncatePosition { |
| 10 |
start = 'start', |
| 11 |
end = 'end', |
| 12 |
middle = 'middle' |
| 13 |
} |
| 14 |
|
| 15 |
const truncateStyles = { |
| 16 |
start: styles.truncateEnd, |
| 17 |
end: styles.truncateStart |
| 18 |
}; |
| 19 |
|
| 20 |
const minWidthCharacters: number = 12; |
| 21 |
|
| 22 |
export interface TruncateProps extends Omit<React.HTMLProps<HTMLSpanElement | HTMLAnchorElement>, 'ref'> { |
| 23 |
/** Class to add to outer span */ |
| 24 |
className?: string; |
| 25 |
/** Text to truncate */ |
| 26 |
content: string; |
| 27 |
/** An HREF to turn the truncate wrapper into an anchor element. For more custom control, use the |
| 28 |
* tooltipProps with a triggerRef property passed in. |
| 29 |
*/ |
| 30 |
href?: string; |
| 31 |
/** The number of characters displayed in the second half of a middle truncation. This will be overridden by |
| 32 |
* the maxCharsDisplayed prop. |
| 33 |
*/ |
| 34 |
trailingNumChars?: number; |
| 35 |
/** The maximum number of characters to display before truncating. This will always truncate content |
| 36 |
* when its length exceeds the value passed to this prop, and container width/resizing will not affect truncation. |
| 37 |
*/ |
| 38 |
maxCharsDisplayed?: number; |
| 39 |
/** The content to use to signify omission of characters when using the maxCharsDisplayed prop. |
| 40 |
* By default this will render an ellipsis. |
| 41 |
*/ |
| 42 |
omissionContent?: string; |
| 43 |
/** Where the text will be truncated */ |
| 44 |
position?: 'start' | 'middle' | 'end'; |
| 45 |
/** Tooltip position */ |
| 46 |
tooltipPosition?: |
| 47 |
| TooltipPosition |
| 48 |
| 'auto' |
| 49 |
| 'top' |
| 50 |
| 'bottom' |
| 51 |
| 'left' |
| 52 |
| 'right' |
| 53 |
| 'top-start' |
| 54 |
| 'top-end' |
| 55 |
| 'bottom-start' |
| 56 |
| 'bottom-end' |
| 57 |
| 'left-start' |
| 58 |
| 'left-end' |
| 59 |
| 'right-start' |
| 60 |
| 'right-end'; |
| 61 |
/** Additional props to pass to the tooltip. */ |
| 62 |
tooltipProps?: Omit<TooltipProps, 'content'>; |
| 63 |
/** @hide Forwarded ref */ |
| 64 |
innerRef?: React.Ref<any>; |
| 65 |
} |
| 66 |
|
| 67 |
const sliceTrailingContent = (str: string, slice: number) => [str.slice(0, str.length - slice), str.slice(-slice)]; |
| 68 |
|
| 69 |
const TruncateBase: React.FunctionComponent<TruncateProps> = ({ |
| 70 |
className, |
| 71 |
href, |
| 72 |
position = 'end', |
| 73 |
tooltipPosition = 'top', |
| 74 |
tooltipProps, |
| 75 |
trailingNumChars = 7, |
| 76 |
maxCharsDisplayed, |
| 77 |
omissionContent = '\u2026', |
| 78 |
content, |
| 79 |
innerRef, |
| 80 |
...props |
| 81 |
}: TruncateProps) => { |
| 82 |
const [isTruncated, setIsTruncated] = useState(true); |
| 83 |
const [parentElement, setParentElement] = useState<HTMLElement>(null); |
| 84 |
const [textElement, setTextElement] = useState<HTMLElement>(null); |
| 85 |
const [shouldRenderByMaxChars, setShouldRenderByMaxChars] = useState(maxCharsDisplayed > 0); |
| 86 |
|
| 87 |
const textRef = useRef<HTMLElement>(null); |
| 88 |
useImperativeHandle(innerRef, () => textRef.current!); |
| 89 |
const defaultSubParentRef = useRef<any>(null); |
| 90 |
const subParentRef = tooltipProps?.triggerRef || defaultSubParentRef; |
| 91 |
const observer = useRef(null); |
| 92 |
|
| 93 |
if (maxCharsDisplayed <= 0) { |
| 94 |
// eslint-disable-next-line no-console |
| 95 |
console.warn('Truncate: the maxCharsDisplayed must be greater than 0, otherwise no content will be visible.'); |
| 96 |
} |
| 97 |
|
| 98 |
const getActualWidth = (element: Element) => { |
| 99 |
const computedStyle = getComputedStyle(element); |
| 100 |
|
| 101 |
return ( |
| 102 |
parseFloat(computedStyle.width) - |
| 103 |
parseFloat(computedStyle.paddingLeft) - |
| 104 |
parseFloat(computedStyle.paddingRight) - |
| 105 |
parseFloat(computedStyle.borderRight) - |
| 106 |
parseFloat(computedStyle.borderLeft) |
| 107 |
); |
| 108 |
}; |
| 109 |
|
| 110 |
const calculateTotalTextWidth = (element: Element, trailingNumChars: number, content: string) => { |
| 111 |
const firstTextWidth = element.scrollWidth; |
| 112 |
const firstTextLength = content.length; |
| 113 |
return (firstTextWidth / firstTextLength) * trailingNumChars + firstTextWidth; |
| 114 |
}; |
| 115 |
|
| 116 |
useEffect(() => { |
| 117 |
if (textRef && textRef.current && !textElement) { |
| 118 |
setTextElement(textRef.current); |
| 119 |
} |
| 120 |
}, [textRef, textElement]); |
| 121 |
|
| 122 |
useEffect(() => { |
| 123 |
const refElement = getReferenceElement(subParentRef); |
| 124 |
if (refElement?.parentElement && !parentElement) { |
| 125 |
setParentElement(refElement.parentElement); |
| 126 |
} |
| 127 |
}, [subParentRef, parentElement]); |
| 128 |
|
| 129 |
useEffect(() => { |
| 130 |
if (textElement && parentElement && !observer.current && !shouldRenderByMaxChars) { |
| 131 |
const totalTextWidth = calculateTotalTextWidth(textElement, trailingNumChars, content); |
| 132 |
const textWidth = position === 'middle' ? totalTextWidth : textElement.scrollWidth; |
| 133 |
|
| 134 |
const debouncedHandleResize = debounce(() => { |
| 135 |
const parentWidth = getActualWidth(parentElement); |
| 136 |
setIsTruncated(textWidth >= parentWidth); |
| 137 |
}, 500); |
| 138 |
|
| 139 |
const observer = getResizeObserver(parentElement, debouncedHandleResize); |
| 140 |
|
| 141 |
return () => { |
| 142 |
observer(); |
| 143 |
}; |
| 144 |
} |
| 145 |
}, [textElement, parentElement, trailingNumChars, content, position, shouldRenderByMaxChars]); |
| 146 |
|
| 147 |
useEffect(() => { |
| 148 |
if (shouldRenderByMaxChars) { |
| 149 |
setIsTruncated(content.length > maxCharsDisplayed); |
| 150 |
} |
| 151 |
}, [shouldRenderByMaxChars, content.length, maxCharsDisplayed]); |
| 152 |
|
| 153 |
useEffect(() => { |
| 154 |
setShouldRenderByMaxChars(maxCharsDisplayed > 0); |
| 155 |
}, [maxCharsDisplayed]); |
| 156 |
|
| 157 |
const lrmEntity = <Fragment>‎</Fragment>; |
| 158 |
const isStartPosition = position === TruncatePosition.start; |
| 159 |
const isEndPosition = position === TruncatePosition.end; |
| 160 |
|
| 161 |
const renderResizeObserverContent = () => { |
| 162 |
if (isEndPosition || isStartPosition) { |
| 163 |
return ( |
| 164 |
<> |
| 165 |
<span ref={textRef} className={truncateStyles[position]}> |
| 166 |
{isStartPosition && lrmEntity} |
| 167 |
{content} |
| 168 |
{isStartPosition && lrmEntity} |
| 169 |
</span> |
| 170 |
</> |
| 171 |
); |
| 172 |
} |
| 173 |
|
| 174 |
const shouldSliceContent = content.length - trailingNumChars > minWidthCharacters; |
| 175 |
return ( |
| 176 |
<> |
| 177 |
<Fragment> |
| 178 |
<span ref={textRef} className={styles.truncateStart}> |
| 179 |
{shouldSliceContent ? sliceTrailingContent(content, trailingNumChars)[0] : content} |
| 180 |
</span> |
| 181 |
{shouldSliceContent && ( |
| 182 |
<span className={styles.truncateEnd}>{sliceTrailingContent(content, trailingNumChars)[1]}</span> |
| 183 |
)} |
| 184 |
</Fragment> |
| 185 |
</> |
| 186 |
); |
| 187 |
}; |
| 188 |
|
| 189 |
const renderMaxDisplayContent = () => { |
| 190 |
const renderVisibleContent = (contentToRender: string) => ( |
| 191 |
<span className={`${styles.truncate}__text`}>{contentToRender}</span> |
| 192 |
); |
| 193 |
if (!isTruncated) { |
| 194 |
return renderVisibleContent(content); |
| 195 |
} |
| 196 |
|
| 197 |
const omissionElement = ( |
| 198 |
<span className={`${styles.truncate}__omission`} aria-hidden="true"> |
| 199 |
{omissionContent} |
| 200 |
</span> |
| 201 |
); |
| 202 |
const renderVisuallyHiddenContent = (contentToHide: string) => ( |
| 203 |
<span className="pf-v6-screen-reader">{contentToHide}</span> |
| 204 |
); |
| 205 |
|
| 206 |
if (position === TruncatePosition.start) { |
| 207 |
return ( |
| 208 |
<> |
| 209 |
{renderVisuallyHiddenContent(content.slice(0, maxCharsDisplayed * -1))} |
| 210 |
{omissionElement} |
| 211 |
{renderVisibleContent(content.slice(maxCharsDisplayed * -1))} |
| 212 |
</> |
| 213 |
); |
| 214 |
} |
| 215 |
if (isEndPosition) { |
| 216 |
return ( |
| 217 |
<> |
| 218 |
{renderVisibleContent(content.slice(0, maxCharsDisplayed))} |
| 219 |
{omissionElement} |
| 220 |
{renderVisuallyHiddenContent(content.slice(maxCharsDisplayed))} |
| 221 |
</> |
| 222 |
); |
| 223 |
} |
| 224 |
|
| 225 |
const trueMiddleStart = Math.floor(maxCharsDisplayed / 2); |
| 226 |
const trueMiddleEnd = Math.ceil(maxCharsDisplayed / 2) * -1; |
| 227 |
return ( |
| 228 |
<> |
| 229 |
{renderVisibleContent(content.slice(0, trueMiddleStart))} |
| 230 |
{omissionElement} |
| 231 |
{renderVisuallyHiddenContent(content.slice(trueMiddleStart, trueMiddleEnd))} |
| 232 |
{renderVisibleContent(content.slice(trueMiddleEnd))} |
| 233 |
</> |
| 234 |
); |
| 235 |
}; |
| 236 |
|
| 237 |
const TruncateWrapper = href ? 'a' : 'span'; |
| 238 |
const truncateBody = ( |
| 239 |
<TruncateWrapper |
| 240 |
ref={!tooltipProps?.triggerRef ? (subParentRef as React.MutableRefObject<any>) : null} |
| 241 |
href={href} |
| 242 |
className={css(styles.truncate, shouldRenderByMaxChars && styles.modifiers.fixed, className)} |
| 243 |
{...(isTruncated && !href && !tooltipProps?.triggerRef && { tabIndex: 0 })} |
| 244 |
{...props} |
| 245 |
> |
| 246 |
{!shouldRenderByMaxChars ? renderResizeObserverContent() : renderMaxDisplayContent()} |
| 247 |
</TruncateWrapper> |
| 248 |
); |
| 249 |
|
| 250 |
return ( |
| 251 |
<> |
| 252 |
{isTruncated && ( |
| 253 |
<Tooltip |
| 254 |
hidden={!isTruncated} |
| 255 |
position={tooltipPosition} |
| 256 |
content={content} |
| 257 |
triggerRef={subParentRef} |
| 258 |
{...tooltipProps} |
| 259 |
/> |
| 260 |
)} |
| 261 |
{truncateBody} |
| 262 |
</> |
| 263 |
); |
| 264 |
}; |
| 265 |
|
| 266 |
export const Truncate = forwardRef((props: TruncateProps, ref: React.Ref<HTMLAnchorElement | HTMLSpanElement>) => ( |
| 267 |
<TruncateBase innerRef={ref} {...props} /> |
| 268 |
)); |
| 269 |
|
| 270 |
Truncate.displayName = 'Truncate'; |