All files / app/src/shared/ui/truncate-container truncate-container.tsx

87.09% Statements 27/31
66.66% Branches 2/3
100% Functions 1/1
87.09% Lines 27/31

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 451x                   1x 19x 19x 19x 19x 19x 19x   19x   19x 19x 19x 19x 19x 19x 19x         19x 19x   19x 19x 19x 19x 19x 19x 19x 19x   19x  
import { useRef, useEffect, useState } from 'react'
import { FCWithClassName, Nullable } from '@/shared/@types'
import { Tooltip } from '../tooltip'
import cn from 'classnames'
export interface TrancateContainerProps {
  maxWidth: number
  children: string
  childrenClassName?: string
}
 
export const TrancateContainer: FCWithClassName<TrancateContainerProps> = ({
  children,
  className,
  maxWidth,
  childrenClassName = '',
}) => {
  const ref = useRef<Nullable<HTMLDivElement>>(null)
 
  const [isTrancated, setIsTrancated] = useState(false)
 
  useEffect(() => {
    if (ref.current) {
      const { current: el } = ref
      const styles = getComputedStyle(el)
      const widthEl = parseFloat(styles.width)
      const ctx = document.createElement('canvas').getContext('2d')
      if (ctx) {
        ctx.font = `${styles.fontSize} ${styles.fontFamily}`
        const text = ctx.measureText(el.innerText)
        if (text.width > widthEl) setIsTrancated(true)
      }
    }
  }, [])
 
  return (
    <div ref={ref} className={className}>
      <Tooltip isActive={isTrancated} label={children}>
        <div className={cn('truncate', childrenClassName)} style={{ maxWidth: maxWidth + 'px' }}>
          {children}
        </div>
      </Tooltip>
    </div>
  )
}