import { useState, useEffect, useCallback, forwardRef } from 'react'; import classNames from 'classnames'; import { AnimatedNumber } from './animated_number'; import type { IconProp } from './icon'; import { Icon } from './icon'; interface Props { className?: string; title: string; icon: string; iconComponent: IconProp; onClick?: React.MouseEventHandler; onMouseDown?: React.MouseEventHandler; onKeyDown?: React.KeyboardEventHandler; onKeyPress?: React.KeyboardEventHandler; active?: boolean; expanded?: boolean; style?: React.CSSProperties; activeStyle?: React.CSSProperties; disabled?: boolean; inverted?: boolean; animate?: boolean; overlay?: boolean; tabIndex?: number; counter?: number; href?: string; ariaHidden?: boolean; data_id?: string; } export const IconButton = forwardRef( ( { className, expanded, icon, iconComponent, inverted, title, counter, href, style, activeStyle, onClick, onKeyDown, onKeyPress, onMouseDown, active = false, disabled = false, animate = false, overlay = false, tabIndex = 0, ariaHidden = false, data_id = undefined, }, buttonRef, ) => { const [activate, setActivate] = useState(false); const [deactivate, setDeactivate] = useState(false); useEffect(() => { if (!animate) { return; } if (activate && !active) { setActivate(false); setDeactivate(true); } else if (!activate && active) { setActivate(true); setDeactivate(false); } }, [setActivate, setDeactivate, animate, active, activate]); const handleClick: React.MouseEventHandler = useCallback( (e) => { e.preventDefault(); if (!disabled) { onClick?.(e); } }, [disabled, onClick], ); const handleKeyPress: React.KeyboardEventHandler = useCallback( (e) => { if (!disabled) { onKeyPress?.(e); } }, [disabled, onKeyPress], ); const handleMouseDown: React.MouseEventHandler = useCallback( (e) => { if (!disabled) { onMouseDown?.(e); } }, [disabled, onMouseDown], ); const handleKeyDown: React.KeyboardEventHandler = useCallback( (e) => { if (!disabled) { onKeyDown?.(e); } }, [disabled, onKeyDown], ); const buttonStyle = { ...style, ...(active ? activeStyle : {}), }; const classes = classNames(className, 'icon-button', { active, disabled, inverted, activate, deactivate, overlayed: overlay, 'icon-button--with-counter': typeof counter !== 'undefined', }); let contents = ( <>