import { CloseOutlined } from '@ant-design/icons'; import { Tag, Tooltip, type TagProps } from 'antd'; import { throttle } from 'lodash'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import TitleTip from './title-tip'; // type TagProps = React.ComponentProps; interface AutoTooltipProps extends Omit { children: React.ReactNode; maxWidth?: number | string; minWidth?: number | string; color?: string; style?: React.CSSProperties; ghost?: boolean; title?: React.ReactNode; showTitle?: boolean; closable?: boolean; tooltipProps?: React.ComponentProps; } const AutoTooltip: React.FC = ({ children, maxWidth = '100%', minWidth, ghost = false, title, showTitle = false, tooltipProps, ...tagProps }) => { const contentRef = useRef(null); const [isOverflowing, setIsOverflowing] = useState(false); const resizeObserver = useRef(null); const checkOverflow = useCallback(() => { if (contentRef.current) { const { scrollWidth, clientWidth } = contentRef.current; setIsOverflowing(scrollWidth > clientWidth); } }, [contentRef.current]); useEffect(() => { const element = contentRef.current; if (!element) return; resizeObserver.current?.disconnect(); resizeObserver.current = new ResizeObserver(() => { checkOverflow(); }); resizeObserver.current?.observe(element); // Initial check checkOverflow(); return () => { resizeObserver.current?.disconnect(); resizeObserver.current = null; }; }, [checkOverflow]); useEffect(() => { const debouncedCheckOverflow = throttle(checkOverflow, 200); window.addEventListener('resize', debouncedCheckOverflow); return () => { window.removeEventListener('resize', debouncedCheckOverflow); debouncedCheckOverflow.cancel(); }; }, [checkOverflow]); useEffect(() => { checkOverflow(); }, [children, checkOverflow]); const tagStyle = useMemo( () => ({ maxWidth, minWidth, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const, ...tagProps.style }), [maxWidth, tagProps.style] ); return ( {children} ) : ( '' ) } {...tooltipProps} > {ghost ? (
{children}
) : ( ) : ( false ) } > {children} )}
); }; export default React.memo(AutoTooltip);