Skip to content

Commit

Permalink
fix: Button accessibility (#7420)
Browse files Browse the repository at this point in the history
* fix: button accessibility

* chore: tabindex -1 when disabled
  • Loading branch information
canerakdas authored Jan 26, 2025
1 parent 1e51ef6 commit 42d2a3c
Showing 1 changed file with 29 additions and 42 deletions.
71 changes: 29 additions & 42 deletions apps/site/components/Common/Button/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
'use client';

import classNames from 'classnames';
import type {
FC,
AnchorHTMLAttributes,
KeyboardEvent,
MouseEvent,
} from 'react';
import type { FC, AnchorHTMLAttributes, ButtonHTMLAttributes } from 'react';

import Link from '@/components/Link';

import styles from './index.module.css';

type ButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
type ButtonProps = (
| AnchorHTMLAttributes<HTMLAnchorElement>
| ButtonHTMLAttributes<HTMLButtonElement>
) & {
kind?: 'neutral' | 'primary' | 'secondary' | 'special';
size?: 'default' | 'small';
disabled?: boolean;
Expand All @@ -22,55 +20,44 @@ const Button: FC<ButtonProps> = ({
kind = 'primary',
size = 'default',
disabled = false,
href = undefined,
children,
className,
onClick,
...props
}) => {
const onKeyDownHandler = (e: KeyboardEvent<HTMLAnchorElement>) => {
if (disabled) {
e.preventDefault();
return;
}

if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (typeof onClick === 'function') {
onClick(e as unknown as MouseEvent<HTMLAnchorElement>);
}
}
};

const onClickHandler = (e: MouseEvent<HTMLAnchorElement>) => {
if (disabled) {
e.preventDefault();
return;
}

if (typeof onClick === 'function') {
onClick(e);
}
};
if ('href' in props) {
return (
<Link
role="button"
href={disabled ? undefined : props.href}
aria-disabled={disabled}
className={classNames(
styles.button,
styles[kind],
styles[size],
className
)}
tabIndex={disabled ? -1 : 0}
{...props}
>
{children}
</Link>
);
}

return (
<Link
role="button"
href={disabled ? undefined : href}
aria-disabled={disabled}
<button
disabled={disabled}
className={classNames(
styles.button,
styles[kind],
styles[size],
className
)}
tabIndex={disabled ? -1 : 0} // Ensure focusable if not disabled
onClick={onClickHandler}
onKeyDown={onKeyDownHandler}
{...props}
type="button"
{...(props as ButtonHTMLAttributes<HTMLButtonElement>)}
>
{children}
</Link>
</button>
);
};

Expand Down

0 comments on commit 42d2a3c

Please sign in to comment.