import React, { FC, useState, MouseEvent, AnchorHTMLAttributes, useContext } from 'react' import _ from 'lodash' import classNames from 'classnames' import { is } from '@gm-common/tool' import { Loading } from '../loading' import { ConfigContext } from '../config_provider' type ButtonType = 'default' | 'primary' | 'success' | 'danger' | 'link' type ButtonSize = 'small' | 'middle' | 'large' type ButtonHTMLType = 'submit' | 'button' | 'reset' interface ButtonProps extends AnchorHTMLAttributes { type?: ButtonType plain?: boolean size?: ButtonSize block?: boolean htmlType?: ButtonHTMLType loading?: boolean href?: string onClick?: (event: MouseEvent) => void disabled?: boolean } const Button: FC = ({ type = 'default', plain, size = 'middle', block, disabled, onClick = _.noop, loading, href, children, htmlType = 'button', className, ...rest }) => { const [isLoading, setIsLoading] = useState(false) const { fontSize } = useContext(ConfigContext) const loadFlag = loading || isLoading const handleClick = ( event: MouseEvent | MouseEvent ) => { if (loadFlag) { return } const result = onClick(event) if (!is.promise(result)) { return } setIsLoading(true) Promise.resolve(result).finally(() => { setIsLoading(false) }) } const Tag = type === 'link' && href ? 'a' : 'button' return ( {loadFlag && (
)} {children}
) } export default Button export type { ButtonProps, ButtonType, ButtonSize, ButtonHTMLType }