import { css } from '@emotion/react'
import { ButtonHTMLAttributes, forwardRef, useCallback, useEffect, useRef } from 'react'
const styles = {
wrapper: css({
'*': {
pointerEvents: 'none',
},
}),
}
export type GAButtonProps = ButtonHTMLAttributes<HTMLButtonElement>
const GAButton = forwardRef<HTMLButtonElement, GAButtonProps>(
({ id, children, 'aria-label': ariaLabel, ...rest }: GAButtonProps, forwardedRef) => {
const inRef = useRef<HTMLButtonElement | null>(null)
const assignRef = useCallback(
(node: HTMLButtonElement) => {
if (forwardedRef) {
if (typeof forwardedRef === 'function') {
forwardedRef(node)
} else {
forwardedRef.current = node
}
}
inRef.current = node
},
[forwardedRef]
)
useEffect(() => {
const button = inRef.current
if (button) {
const slugifiedButtonText = (ariaLabel ?? button?.textContent ?? '')?.trim().replaceAll(' ', '-')
if (!id) {
button.setAttribute('id', `button--${slugifiedButtonText}`)
}
const textColor = window.getComputedStyle(button).color
button.style.setProperty('--text-color', textColor)
}
}, [ariaLabel, children, id])
return (
<button ref={assignRef} id={id} aria-label={ariaLabel} css={styles.wrapper} {...rest}>
{children}
</button>
)
}
)
GAButton.displayName = 'GAButton'
export default GAButton