import {
HTMLAttributes,
isValidElement,
MouseEvent,
MouseEventHandler,
Ref,
useEffect,
useRef,
useState,
} from 'react'
import {cx, createDelayHandler, DelayHandler, isPromiseLike, omit, isNumber, isUndefined} from '@befe/brick-utils'
import {Icon} from '@befe/brick-comp-icon'
import {SvgLoading} from '@befe/brick-icon'
import {useTheme} from '@befe/brick-core'
import {ButtonProps} from './base'
import {normalizeColor} from './deprecated'
const ButtonLoadingIcon = () =>
const NO_NORMAL_TYPE_LIST: Array = ['intensive', 'important']
const ONLY_NORMAL_TYPE_LIST: Array = ['normal', 'ghost']
// color 归一(含 deprecated primary→brand)+ 按 type / icon-only 落位
function resolveButtonColor(
type: ButtonProps['type'],
rawColor: ButtonProps['color'],
isIconOnly: boolean
): ButtonProps['color'] {
const color = normalizeColor(rawColor)
if (color && color !== 'normal' && !ONLY_NORMAL_TYPE_LIST.includes(type)) {
return color
}
if (isIconOnly && type === 'plain') {
return 'normal'
}
if (type && NO_NORMAL_TYPE_LIST.includes(type)) {
return 'brand'
}
return 'normal'
}
// 主题默认落位:prop 优先,未传回落主题默认(对应 class getDefaultValueUsingTheme / getThemeValue)
function resolveButtonDefaults(props: ButtonProps, theme: ReturnType) {
return {
size: props.size ?? theme.baseSize,
shape: props.shape ?? theme.buttonDefaultShape,
loadingIcon: (props.loadingIcon ?? theme.buttonLoadingIcon) || ButtonLoadingIcon,
loadingType: props.loadingType ?? theme.buttonLoadingType,
loadingDelay: props.loadingDelay ?? theme.loadingDelay,
}
}
function resolveButtonHref(href: ButtonProps['href'], disabled: boolean) {
return href && !disabled ? href : undefined
}
// content-icon-only:无 icon prop 但 children 本身是单个
function isContentIconOnlyElement(icon: ButtonProps['icon'], children: ButtonProps['children']) {
return !icon && !!children && isValidElement(children) && children.type === Icon
}
type ButtonLoadingIconValue = NonNullable | typeof ButtonLoadingIcon
// 内层内容(loading icon + button icon + content),抽为 render 辅助以降复杂度
function renderButtonInner(view: {
showLoading: boolean
loadingIcon: ButtonLoadingIconValue
loadingType: ButtonProps['loadingType']
icon: ButtonProps['icon']
children: ButtonProps['children']
}) {
const {showLoading, loadingIcon, loadingType, icon, children} = view
const loadingIconNode = showLoading
? (
)
: null
const buttonIconNode = icon ? : null
const content = !children && !isNumber(children)
? null
: {children}
return (
{loadingIconNode}
{loadingType === 'icon-only' || !showLoading ? buttonIconNode : null}
{content}
)
}
export function Button(props: ButtonProps) {
const {
className: customClassName,
type = 'normal',
disabled = false,
icon,
children,
target,
download,
loading,
refHTMLElement,
} = props
const [showLoading, setShowLoadingState] = useState(!!loading)
const [asyncLoading, setAsyncLoading] = useState(false)
const showLoadingHandlerRef = useRef()
// React 17 下异步 onClick 的 promise 可能在组件卸载后 resolve,用挂载标记守卫 finally 里的 setState,
// 避免「卸载后更新 state」告警(见 `unmount before promise resolved` 用例);React 18 起该告警移除后可去掉
const isMountedRef = useRef(false)
const {size, shape, loadingIcon, loadingType, loadingDelay} = resolveButtonDefaults(props, useTheme())
const isUncontrolledLoading = typeof loading !== 'boolean'
const isIconOnly = !!(icon && !children)
const isContentIconOnly = isContentIconOnlyElement(icon, children)
const isColorUnset = isUndefined(props.color)
const color = resolveButtonColor(type, props.color, isIconOnly)
const href = resolveButtonHref(props.href, disabled)
const className = cx(
'brick-button',
customClassName,
`brick-button-size-${size}`,
`brick-button-shape-${shape}`,
`brick-button-type-${type}`,
`brick-button-loading-type-${loadingType}`,
`brick-button-color-${color}`,
{
'brick-button-disabled': disabled,
'brick-button-icon-only': isIconOnly,
'brick-button-content-icon-only': isContentIconOnly,
'brick-button-loading': showLoading,
// 仅 icon-only + plain 且未显式指定 color 时,图标沿用原始 icon 色板
'brick-button-original-icon-color': isColorUnset && isIconOnly && type === 'plain',
}
)
const setShowLoading = (next: boolean) => {
showLoadingHandlerRef.current?.clear()
setShowLoadingState(next)
}
const handleClick = (e: MouseEvent & MouseEvent) => {
const {onClick} = props
if (disabled || loading || asyncLoading) {
return
}
if (typeof onClick === 'function') {
const ret = onClick(e)
if (isUncontrolledLoading && ret && isPromiseLike(ret)) {
setAsyncLoading(true)
showLoadingHandlerRef.current?.()
void ret.finally(() => {
if (!isMountedRef.current) {
return
}
setAsyncLoading(false)
setShowLoading(false)
})
}
}
}
// 挂载时创建 loading 延时 handler,卸载时清理(对应 class didMount / willUnmount)
useEffect(() => {
isMountedRef.current = true
showLoadingHandlerRef.current = createDelayHandler(() => setShowLoadingState(true), loadingDelay)
return () => {
isMountedRef.current = false
showLoadingHandlerRef.current?.clear()
}
// 仅挂载时建 handler;loadingDelay 的后续变化由下方 effect 跟进
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// loadingDelay 变化 → 更新 handler 延时(须在受控同步 effect 之前,保证先更新再调度)
useEffect(() => {
showLoadingHandlerRef.current?.updateDelayTime(loadingDelay)
}, [loadingDelay])
// 受控 loading 同步(对应 class didUpdate 的 loading 处理)
useEffect(() => {
if (isUncontrolledLoading || showLoading === loading) {
return
}
if (loading) {
showLoadingHandlerRef.current?.()
} else {
showLoadingHandlerRef.current?.clear()
setShowLoadingState(false)
}
}, [loading, showLoading, isUncontrolledLoading])
// 元素无关的共用透传 props。
// omit 结果仍带 ButtonProps 混合的 button + anchor 属性,收窄成公共基类 HTMLAttributes,
// 使其能干净地 spread 到