feat: add accessible Tooltip component with hover, focus, and tap support

This commit is contained in:
Jose Selesan
2026-09-29 20:12:06 -03:00
parent 9520763ec3
commit 8ccff20473
22 changed files with 1317 additions and 126 deletions

View File

@@ -1,8 +1,9 @@
export { Avatar, type AvatarProps } from './avatar'
export { Button, type ButtonProps, type ButtonVariant, type ButtonSize } from './button'
export { Badge, type BadgeProps, type BadgeVariant } from './badge'
export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button'
export { Input, type InputProps } from './input'
export { Label, type LabelProps } from './label'
export { Modal, type ModalProps } from './modal'
export { ToastProvider, useToast, type ToastType, type Toast } from './toast'
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
export { Tooltip, type TooltipProps } from './tooltip'

View 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>
)
}