Files

48 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-09-18 13:38:17 +08:00
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
2024-06-18 12:50:33 +08:00
import clsx from "clsx";
2024-09-18 13:38:17 +08:00
import { Children, forwardRef, memo, ReactNode, useImperativeHandle, useRef } from "react";
import "./button.less";
2024-06-18 12:50:33 +08:00
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
className?: string;
2024-09-18 13:38:17 +08:00
children?: ReactNode;
}
2024-09-18 13:38:17 +08:00
const Button = memo(
2024-09-20 09:55:28 +08:00
forwardRef<HTMLButtonElement, ButtonProps>(({ children, disabled, className = "", ...props }: ButtonProps, ref) => {
const btnRef = useRef<HTMLButtonElement>(null);
useImperativeHandle(ref, () => btnRef.current as HTMLButtonElement);
2024-09-20 09:55:28 +08:00
const childrenArray = Children.toArray(children);
2024-09-17 13:23:05 +08:00
2024-09-20 09:55:28 +08:00
// Check if the className contains any of the categories: solid, outlined, or ghost
const containsButtonCategory = /(solid|outline|ghost)/.test(className);
// If no category is present, default to 'solid'
const categoryClassName = containsButtonCategory ? className : `solid ${className}`;
2024-09-17 13:23:05 +08:00
2024-09-20 09:55:28 +08:00
// Check if the className contains any of the color options: green, grey, red, or yellow
const containsColor = /(green|grey|red|yellow)/.test(categoryClassName);
// If no color is present, default to 'green'
const finalClassName = containsColor ? categoryClassName : `green ${categoryClassName}`;
2024-09-18 13:38:17 +08:00
2024-09-20 09:55:28 +08:00
return (
<button
ref={btnRef}
tabIndex={disabled ? -1 : 0}
className={clsx("button", finalClassName)}
disabled={disabled}
{...props}
>
{childrenArray}
</button>
);
})
2024-09-18 13:38:17 +08:00
);
2024-09-20 09:55:28 +08:00
Button.displayName = "Button";
export { Button };