Path: blob/1.0-develop/resources/scripts/components/elements/tooltip/Tooltip.tsx
10288 views
import React, { cloneElement, useRef, useState } from 'react';1import {2arrow,3autoUpdate,4flip,5offset,6Placement,7shift,8Side,9useClick,10useDismiss,11useFloating,12useFocus,13useHover,14useInteractions,15useRole,16} from '@floating-ui/react-dom-interactions';17import { AnimatePresence, motion } from 'framer-motion';18import classNames from 'classnames';1920type Interaction = 'hover' | 'click' | 'focus';2122interface Props {23rest?: number;24delay?: number | Partial<{ open: number; close: number }>;25content: string | React.ReactChild;26disabled?: boolean;27arrow?: boolean;28interactions?: Interaction[];29placement?: Placement;30className?: string;31children: React.ReactElement;32}3334const arrowSides: Record<Side, string> = {35top: 'bottom-[-6px] left-0',36bottom: 'top-[-6px] left-0',37right: 'top-0 left-[-6px]',38left: 'top-0 right-[-6px]',39};4041export default ({ children, ...props }: Props) => {42const arrowEl = useRef<HTMLDivElement>(null);43const [open, setOpen] = useState(false);4445const { x, y, reference, floating, middlewareData, strategy, context } = useFloating({46open,47strategy: 'fixed',48placement: props.placement || 'top',49middleware: [50offset(props.arrow ? 10 : 6),51flip(),52shift({ padding: 6 }),53arrow({ element: arrowEl, padding: 6 }),54],55onOpenChange: setOpen,56whileElementsMounted: autoUpdate,57});5859const interactions = props.interactions || ['hover', 'focus'];60const { getReferenceProps, getFloatingProps } = useInteractions([61useHover(context, {62restMs: props.rest ?? 30,63delay: props.delay ?? 0,64enabled: interactions.includes('hover'),65}),66useFocus(context, { enabled: interactions.includes('focus') }),67useClick(context, { enabled: interactions.includes('click') }),68useRole(context, { role: 'tooltip' }),69useDismiss(context),70]);7172const side = arrowSides[(props.placement || 'top').split('-')[0] as Side];73const { x: ax, y: ay } = middlewareData.arrow || {};7475if (props.disabled) {76return children;77}7879return (80<>81{cloneElement(children, getReferenceProps({ ref: reference, ...children.props }))}82<AnimatePresence>83{open && (84<motion.div85initial={{ opacity: 0, scale: 0.85 }}86animate={{ opacity: 1, scale: 1 }}87exit={{ opacity: 0 }}88transition={{ type: 'spring', damping: 20, stiffness: 300, duration: 0.075 }}89{...getFloatingProps({90ref: floating,91className:92'bg-gray-900 text-sm text-gray-200 px-3 py-2 rounded pointer-events-none max-w-[24rem]',93style: {94position: strategy,95top: `${y || 0}px`,96left: `${x || 0}px`,97},98})}99>100{props.content}101{props.arrow && (102<div103ref={arrowEl}104style={{105transform: `translate(${Math.round(ax || 0)}px, ${Math.round(106ay || 0107)}px) rotate(45deg)`,108}}109className={classNames('absolute bg-gray-900 w-3 h-3', side)}110/>111)}112</motion.div>113)}114</AnimatePresence>115</>116);117};118119120