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 focus #7287

Merged
merged 14 commits into from
Dec 16, 2024
Merged
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
63 changes: 50 additions & 13 deletions apps/site/components/Common/Button/index.tsx
ovflowd marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
'use client';

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

import Link from '@/components/Link';

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

type ButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
kind?: 'neutral' | 'primary' | 'secondary' | 'special';
// We have an extra `disabled` prop as we simulate a button
disabled?: boolean;
};

Expand All @@ -17,17 +23,48 @@ const Button: FC<ButtonProps> = ({
href = undefined,
children,
className,
onClick,
...props
}) => (
<Link
role="button"
href={disabled ? undefined : href}
aria-disabled={disabled}
className={classNames(styles.button, styles[kind], className)}
{...props}
>
{children}
</Link>
);
}) => {
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);
}
};

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

export default Button;
Loading