|
| 1 | +import React, { useEffect, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +interface GlossaryTooltipProps { |
| 4 | + term: string; |
| 5 | + definition: string; |
| 6 | + children: React.ReactNode; |
| 7 | +} |
| 8 | + |
| 9 | +const GlossaryTooltip: React.FC<GlossaryTooltipProps> = ({ term, definition, children }) => { |
| 10 | + const tooltipRef = useRef<HTMLDivElement>(null); |
| 11 | + const [tooltipPosition, setTooltipPosition] = useState<{ top: number; left: number } | null>(null); |
| 12 | + |
| 13 | + const handleMouseEnter = (event: React.MouseEvent) => { |
| 14 | + const target = event.currentTarget; |
| 15 | + |
| 16 | + // Get the bounding rectangle of the target element. |
| 17 | + const rect = target.getBoundingClientRect(); |
| 18 | + |
| 19 | + // Calculate tooltip position. |
| 20 | + const tooltipTop = rect.bottom + window.scrollY; // Position below the term. |
| 21 | + const tooltipLeft = rect.left + window.scrollX; // Align with the left edge of the term. |
| 22 | + |
| 23 | + setTooltipPosition({ top: tooltipTop, left: tooltipLeft }); |
| 24 | + }; |
| 25 | + |
| 26 | + const handleMouseLeave = () => { |
| 27 | + setTooltipPosition(null); |
| 28 | + }; |
| 29 | + |
| 30 | + return ( |
| 31 | + <> |
| 32 | + <span |
| 33 | + onMouseEnter={handleMouseEnter} |
| 34 | + onMouseLeave={handleMouseLeave} |
| 35 | + className="glossary-term" |
| 36 | + > |
| 37 | + {children} |
| 38 | + </span> |
| 39 | + |
| 40 | + {tooltipPosition && ( |
| 41 | + <div |
| 42 | + ref={tooltipRef} |
| 43 | + className="tooltip-glossary" |
| 44 | + style={{ |
| 45 | + top: tooltipPosition.top, |
| 46 | + left: tooltipPosition.left, |
| 47 | + position: 'absolute', |
| 48 | + }} |
| 49 | + > |
| 50 | + {definition} |
| 51 | + </div> |
| 52 | + )} |
| 53 | + </> |
| 54 | + ); |
| 55 | +}; |
| 56 | + |
| 57 | +export default GlossaryTooltip; |
0 commit comments