import React, { AnchorHTMLAttributes, ComponentType, createElement, CSSProperties, ReactNode, useCallback } from 'react'
import cln from 'classnames'
import { usePrefix } from '../ConfigProvider'
import { concat } from '../utils'
import { RightThinIcon } from '../icons'
import { useEnv } from './env'
import { WithRef } from '../utils/type'
export type LinkType = 'blue' | 'black' | 'classic'
export type LinkProps = {
title?: string
/** 跳转链接 */
href?: string
/** 打开链接文档的方式 */
target?: string
/** 表示当前文档和链接之间的关系 */
rel?: string
/** 当用户点击时被下载的目标 */
download?: any
onClick?(event: React.MouseEvent): void
/** 内容 */
children?: ReactNode
/** 自定义样式名 */
className?: string
/** 自定义样式 */
style?: CSSProperties
as?: ComponentType, T>>
icon?: ReactNode
/**
* + black - 黑色,会在尾部追加一个箭头
* + blue - 蓝色
* + classic - hover 会有下划线,颜色继承环境色
*
* @default 'blue'
*/
type?: LinkType
/**
* 根元素的 html 属性
*/
rootHtmlProps?: WithRef, T>
}
export default function Link(props: LinkProps) {
const { as, className, children, type = 'blue', icon, rootHtmlProps, style, onClick, ...rest } = props
const prefix = usePrefix('link')
const isBlueEnv = useEnv().isBlue
const classname = cln(
prefix, className,
concat(prefix, type),
isBlueEnv && concat(prefix, 'env', 'blue'),
rootHtmlProps?.className
)
const handleClick = useCallback((e: React.MouseEvent) => {
rootHtmlProps?.onClick?.(e)
if (e.defaultPrevented) return
onClick?.(e)
}, [rootHtmlProps, onClick])
const rootProps = {
...rest,
...rootHtmlProps,
onClick: (rootHtmlProps?.onClick || onClick) && handleClick,
className: classname,
style: { ...style, ...rootHtmlProps?.style }
}
const suffix = type === 'black' ? <> > : null
return (
createElement(as ?? 'a', rootProps, (
<>
{icon && {icon}}
{children}{suffix}
>
))
)
}