|
1 | | -import { useState, useId } from 'react' |
2 | | -import { cx } from 'class-variance-authority' |
| 1 | +import { useState } from 'react' |
| 2 | +import { |
| 3 | + useFloating, |
| 4 | + offset, |
| 5 | + flip, |
| 6 | + shift, |
| 7 | + autoUpdate, |
| 8 | + size |
| 9 | +} from '@floating-ui/react-dom' |
3 | 10 | import { SVGTooltip } from '../../../assets/svg' |
4 | 11 |
|
5 | 12 | export interface TooltipProps { |
6 | 13 | children: React.ReactNode |
7 | | - className?: string |
8 | 14 | } |
9 | 15 |
|
10 | | -export function Tooltip({ children, className }: TooltipProps) { |
| 16 | +export function Tooltip({ children }: TooltipProps) { |
11 | 17 | const [open, setOpen] = useState(false) |
12 | | - const tooltipId = useId() |
| 18 | + |
| 19 | + const { x, y, strategy, refs } = useFloating({ |
| 20 | + open, |
| 21 | + placement: 'right', |
| 22 | + middleware: [ |
| 23 | + offset(8), |
| 24 | + flip({ |
| 25 | + fallbackPlacements: ['top', 'bottom'], |
| 26 | + padding: 8 |
| 27 | + }), |
| 28 | + shift({ padding: 8 }), |
| 29 | + size({ |
| 30 | + apply({ availableWidth, elements }) { |
| 31 | + const maxWidth = Math.min(availableWidth, 450) |
| 32 | + Object.assign(elements.floating.style, { |
| 33 | + maxWidth: `${maxWidth}px`, |
| 34 | + width: 'auto' |
| 35 | + }) |
| 36 | + }, |
| 37 | + padding: 8 |
| 38 | + }) |
| 39 | + ], |
| 40 | + whileElementsMounted: autoUpdate |
| 41 | + }) |
13 | 42 |
|
14 | 43 | return ( |
15 | | - <div className={cx('w-fit relative inline-flex', className)}> |
| 44 | + <> |
16 | 45 | <button |
| 46 | + ref={refs.setReference} |
17 | 47 | type="button" |
18 | 48 | aria-label="More information" |
19 | | - aria-describedby={open ? tooltipId : undefined} |
20 | | - aria-expanded={open} |
| 49 | + aria-describedby={open ? 'tooltip' : undefined} |
21 | 50 | onMouseEnter={() => setOpen(true)} |
22 | 51 | onMouseLeave={() => setOpen(false)} |
23 | 52 | onFocus={() => setOpen(true)} |
24 | 53 | onBlur={() => setOpen(false)} |
25 | | - onClick={() => setOpen(!open)} |
26 | 54 | className="rounded-full hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-primary-focus" |
27 | 55 | > |
28 | 56 | <SVGTooltip className="w-6 h-6" /> |
29 | 57 | </button> |
30 | 58 |
|
31 | 59 | {open && ( |
32 | 60 | <div |
33 | | - id={tooltipId} |
| 61 | + ref={refs.setFloating} |
| 62 | + id="tooltip" |
34 | 63 | role="tooltip" |
35 | | - className="absolute z-50 left-8 top-1/2 -translate-y-1/2 w-[485px] flex items-center justify-center gap-2.5 p-4 bg-interface-tooltip rounded-lg shadow-lg" |
| 64 | + style={{ |
| 65 | + position: strategy, |
| 66 | + top: y, |
| 67 | + left: x |
| 68 | + }} |
| 69 | + className="z-50 p-md bg-interface-tooltip rounded-lg shadow-lg text-white text-xs sm:text-sm" |
36 | 70 | > |
37 | | - <p className="text-white text-sm leading-relaxed">{children}</p> |
| 71 | + {children} |
38 | 72 | </div> |
39 | 73 | )} |
40 | | - </div> |
| 74 | + </> |
41 | 75 | ) |
42 | 76 | } |
0 commit comments