Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(button.tsx): Button as prop internal logic + TS props #885

Merged
merged 5 commits into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/docs/components/button/button.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ The `as` prop provides you the ability to transform the `<Button />` component i
<Button as="span" className="cursor-pointer">Span Button</Button>
</div>
<div>
<Button as={Link} href="#">
<Button as={Link} href="/">
Next Link Button
</Button>
</div>
Expand All @@ -256,7 +256,7 @@ The `as` prop provides you the ability to transform the `<Button />` component i
</Button>
</div>
<div>
<Button as={Link} href="#">
<Button as={Link} href="/">
Next Link Button
</Button>
</div>
Expand Down
4 changes: 2 additions & 2 deletions app/docs/components/dropdown/dropdown.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ To customize the `Dropdown.Item` base element you can use the `as` property.
<Dropdown.Item as={Link} href="/">
Home
</Dropdown.Item>
<Dropdown.Item href="https://flowbite.com/" target="_blank">
<Dropdown.Item as="a" href="https://flowbite.com/" target="_blank">
External link
</Dropdown.Item>
</Dropdown>`}
Expand All @@ -212,7 +212,7 @@ To customize the `Dropdown.Item` base element you can use the `as` property.
<Dropdown.Item as={Link} href="/">
Home
</Dropdown.Item>
<Dropdown.Item href="https://flowbite.com/" target="_blank">
<Dropdown.Item as="a" href="https://flowbite.com/" target="_blank">
External link
</Dropdown.Item>
</Dropdown>
Expand Down
44 changes: 29 additions & 15 deletions src/components/Button/Button.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,41 +125,55 @@ describe('Components / Button', () => {
expect(buttonLink()).toBeInTheDocument();
});

it('should render an anchor `<a>` when `href=".."` even though `as` is defined', () => {
render(<Button href="#" as="label" label="Something or other" />);

expect(buttonLink()).toBeInTheDocument();
});
it('should render component defined in `as`', () => {
const CustomComponent = ({ children }: PropsWithChildren<{ uniqueProp: boolean }>) => {
return <li>{children}</li>;
};

it('should render tag element defined in `as`', () => {
render(
<ul>
<Button as="li" label="Something or other" />
<Button as={CustomComponent} uniqueProp>
Something or other
</Button>
</ul>,
);

expect(buttonListItem()).toBeInTheDocument();
const button = buttonListItem();

expect(button).toBeInTheDocument();
expect(button).toHaveTextContent('Something or other');
});

it('should render component defined in `as`', () => {
it('should render component defined in `as` prop even though `href` is defined', () => {
const CustomComponent = ({ children }: PropsWithChildren) => {
return <li>{children}</li>;
};

render(
<ul>
<Button as={CustomComponent} label="Something or other" />
<Button href="#" as={CustomComponent} label="Something or other" />
</ul>,
);

const button = buttonListItem();
expect(buttonListItem()).toBeInTheDocument();
});

expect(button).toBeInTheDocument();
expect(button).toHaveTextContent('Something or other');
it('should render tag element defined in `as`', () => {
render(
<ul>
<Button as="li" label="Something or other" />
</ul>,
);

expect(buttonListItem()).toBeInTheDocument();
});

it('should render as button when `as`={null}', () => {
render(<Button as={null} label="Something or other" />);
it('should render as button `as={null}`', () => {
render(
<ul>
<Button as={null as any} label="Something or other" />
</ul>,
);

expect(button()).toBeInTheDocument();
});
Expand Down
155 changes: 78 additions & 77 deletions src/components/Button/Button.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { forwardRef, type ReactNode } from 'react';
import type { ComponentPropsWithoutRef, ElementType, ForwardedRef } from 'react';
import { type ReactNode } from 'react';
import { twMerge } from 'tailwind-merge';
import genericForwardRef from '~/src/helpers/generic-forward-ref';
import type {
DeepPartial,
FlowbiteBoolean,
Expand Down Expand Up @@ -64,7 +66,9 @@ export interface ButtonSizes extends Pick<FlowbiteSizes, 'xs' | 'sm' | 'lg' | 'x
[key: string]: string;
}

export interface ButtonProps extends ButtonBaseProps {
export type ButtonProps<T extends ElementType = 'button'> = {
as?: T;
href?: string;
color?: keyof FlowbiteColors;
fullSized?: boolean;
gradientDuoTone?: keyof ButtonGradientDuoToneColors;
Expand All @@ -79,88 +83,85 @@ export interface ButtonProps extends ButtonBaseProps {
positionInGroup?: keyof PositionInButtonGroup;
size?: keyof ButtonSizes;
theme?: DeepPartial<FlowbiteButtonTheme>;
}

interface Props extends ButtonProps, Record<string, unknown> {}
} & ComponentPropsWithoutRef<T>;

const ButtonComponent = forwardRef<HTMLButtonElement | HTMLAnchorElement, Props>(
(
{
children,
className,
color = 'info',
disabled = false,
fullSized,
isProcessing = false,
processingLabel = 'Loading...',
processingSpinner,
gradientDuoTone,
gradientMonochrome,
label,
outline = false,
pill = false,
positionInGroup = 'none',
size = 'md',
theme: customTheme = {},
...props
},
ref,
) => {
const { buttonGroup: groupTheme, button: buttonTheme } = useTheme().theme;
const theme = mergeDeep(buttonTheme, customTheme);
const ButtonComponentFn = <T extends ElementType = 'button'>(
{
children,
className,
color = 'info',
disabled,
fullSized,
isProcessing = false,
processingLabel = 'Loading...',
processingSpinner,
gradientDuoTone,
gradientMonochrome,
label,
outline = false,
pill = false,
positionInGroup = 'none',
size = 'md',
theme: customTheme = {},
...props
}: ButtonProps<T>,
ref: ForwardedRef<T>,
) => {
const { buttonGroup: groupTheme, button: buttonTheme } = useTheme().theme;
const theme = mergeDeep(buttonTheme, customTheme);

const theirProps = props as object;
const theirProps = props as ButtonBaseProps<T>;

return (
<ButtonBase
disabled={disabled}
ref={ref as never}
return (
<ButtonBase
ref={ref}
disabled={disabled}
className={twMerge(
theme.base,
disabled && theme.disabled,
!gradientDuoTone && !gradientMonochrome && theme.color[color],
gradientDuoTone && !gradientMonochrome && theme.gradientDuoTone[gradientDuoTone],
!gradientDuoTone && gradientMonochrome && theme.gradient[gradientMonochrome],
outline && (theme.outline.color[color] ?? theme.outline.color.default),
theme.pill[pill ? 'on' : 'off'],
fullSized && theme.fullSized,
groupTheme.position[positionInGroup],
className,
)}
{...theirProps}
>
<span
className={twMerge(
theme.base,
disabled && theme.disabled,
!gradientDuoTone && !gradientMonochrome && theme.color[color],
gradientDuoTone && !gradientMonochrome && theme.gradientDuoTone[gradientDuoTone],
!gradientDuoTone && gradientMonochrome && theme.gradient[gradientMonochrome],
outline && (theme.outline.color[color] ?? theme.outline.color.default),
theme.pill[pill ? 'on' : 'off'],
fullSized && theme.fullSized,
groupTheme.position[positionInGroup],
className,
theme.inner.base,
theme.outline[outline ? 'on' : 'off'],
theme.outline.pill[outline && pill ? 'on' : 'off'],
theme.size[size],
outline && !theme.outline.color[color] && theme.inner.outline,
isProcessing && theme.isProcessing,
isProcessing && theme.inner.isProcessingPadding[size],
theme.inner.position[positionInGroup],
)}
{...theirProps}
>
<span
className={twMerge(
theme.inner.base,
theme.outline[outline ? 'on' : 'off'],
theme.outline.pill[outline && pill ? 'on' : 'off'],
theme.size[size],
outline && !theme.outline.color[color] && theme.inner.outline,
isProcessing && theme.isProcessing,
isProcessing && theme.inner.isProcessingPadding[size],
theme.inner.position[positionInGroup],
<>
{isProcessing && (
<span className={twMerge(theme.spinnerSlot, theme.spinnerLeftPosition[size])}>
{processingSpinner || <Spinner size={size} />}
</span>
)}
>
<>
{isProcessing && (
<span className={twMerge(theme.spinnerSlot, theme.spinnerLeftPosition[size])}>
{processingSpinner || <Spinner size={size} />}
</span>
)}
{typeof children !== 'undefined' ? (
children
) : (
<span data-testid="flowbite-button-label" className={twMerge(theme.label)}>
{isProcessing ? processingLabel : label}
</span>
)}
</>
</span>
</ButtonBase>
);
},
);
ButtonComponent.displayName = 'ButtonComponent';
{typeof children !== 'undefined' ? (
children
) : (
<span data-testid="flowbite-button-label" className={twMerge(theme.label)}>
{isProcessing ? processingLabel : label}
</span>
)}
</>
</span>
</ButtonBase>
);
};

const ButtonComponent = genericForwardRef(ButtonComponentFn);

export const Button = Object.assign(ButtonComponent, {
Group: ButtonGroup,
Expand Down
26 changes: 13 additions & 13 deletions src/components/Button/ButtonBase.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { createElement, forwardRef, type ComponentProps, type ElementType } from 'react';
import { createElement, type ComponentPropsWithoutRef, type ElementType, type ForwardedRef } from 'react';
import genericForwardRef from '../../helpers/generic-forward-ref';

export interface ButtonBaseProps extends Omit<ComponentProps<'button'>, 'color' | 'ref'> {
as?: ElementType;
export type ButtonBaseProps<T extends ElementType = 'button'> = {
as?: T;
href?: string;
}
} & ComponentPropsWithoutRef<T>;

interface Props extends ButtonBaseProps, Record<string, unknown> {}
const ButtonBaseComponent = <T extends ElementType = 'button'>(
{ children, as: Component, href, type = 'button', ...props }: ButtonBaseProps<T>,
ref: ForwardedRef<T>,
) => {
const BaseComponent = Component || (href ? 'a' : 'button');

export const ButtonBase = forwardRef<HTMLButtonElement | HTMLAnchorElement, Props>(
({ children, as: Component = 'button', href, ...props }, ref) => {
const BaseComponent = href ? 'a' : Component ?? 'button';
const type = Component === 'button' ? 'button' : undefined;
return createElement(BaseComponent, { ref, href, type, ...props }, children);
};

return createElement(BaseComponent, { ref, href, type, ...props }, children);
},
);
ButtonBase.displayName = 'Button';
export const ButtonBase = genericForwardRef(ButtonBaseComponent);
2 changes: 1 addition & 1 deletion src/components/Dropdown/Dropdown.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ CustomItem.args = {
<Dropdown.Item>Default button</Dropdown.Item>
<Dropdown.Item as="span">As span</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Item href="https://flowbite.com/" target="_blank">
<Dropdown.Item as="a" href="https://flowbite.com/" target="_blank">
As link
</Dropdown.Item>
</>
Expand Down
10 changes: 8 additions & 2 deletions src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
PropsWithChildren,
ReactElement,
ReactNode,
RefCallback,
SetStateAction,
} from 'react';
import { cloneElement, createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';
Expand Down Expand Up @@ -101,7 +102,13 @@ const Trigger = ({
{children}
</button>
) : (
<Button {...buttonProps} disabled={disabled} type="button" ref={refs.setReference} {...a11yProps}>
<Button
{...buttonProps}
disabled={disabled}
type="button"
ref={refs.setReference as RefCallback<'button'>}
{...a11yProps}
>
{children}
</Button>
);
Expand Down Expand Up @@ -247,7 +254,6 @@ const DropdownComponent: FC<DropdownProps> = ({
};

DropdownComponent.displayName = 'Dropdown';
DropdownItem.displayName = 'Dropdown.Item';
DropdownHeader.displayName = 'Dropdown.Header';
DropdownDivider.displayName = 'Dropdown.Divider';

Expand Down
Loading