feat: add accessible Tooltip component with hover, focus, and tap support
This commit is contained in:
67
apps/web/src/components/ui/tooltip.tsx
Normal file
67
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import { type ReactNode, useId, useState } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export type TooltipProps = {
|
||||
/** Texto explicativo que se muestra al hacer hover, foco de teclado o tap. */
|
||||
content: ReactNode
|
||||
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en sm+). */
|
||||
tooltipClassName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Tooltip accesible sin dependencias: hover (ratón), foco (teclado) y tap
|
||||
* (táctil, vía focus). Se cierra con Escape, al salir el puntero o al perder
|
||||
* el foco. El globo se ancla abajo del disparador para no tapar el contenido.
|
||||
*/
|
||||
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const id = useId()
|
||||
|
||||
const show = () => setOpen(true)
|
||||
const hide = () => setOpen(false)
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
aria-describedby={open ? id : undefined}
|
||||
// El hover solo aplica a punteros de ratón: en táctil no hay "hover
|
||||
// persistente" y el tap se resuelve con focus + click.
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType === 'mouse') show()
|
||||
}}
|
||||
onPointerLeave={(e) => {
|
||||
if (e.pointerType === 'mouse') hide()
|
||||
}}
|
||||
onFocus={show}
|
||||
onBlur={hide}
|
||||
onClick={show}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') hide()
|
||||
}}
|
||||
className={cn(
|
||||
'inline-flex cursor-help rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<span
|
||||
id={id}
|
||||
role="tooltip"
|
||||
className={cn(
|
||||
'absolute top-full left-0 z-50 mt-1.5 w-max max-w-[min(16rem,calc(100vw_-_2rem))] rounded-lg border border-border bg-surface px-2.5 py-2 text-xs leading-snug text-foreground shadow-sm animate-fade-in sm:left-auto sm:right-0',
|
||||
tooltipClassName,
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user