Skip to content

Commit

Permalink
Fix button focus (nodejs#7287)
Browse files Browse the repository at this point in the history
* add changes to MetaBar index.modul.css

* add href to button

* remove unrelated changes

* apply changes to CodeBox file & Button file

* add change to CodeBox file

* add changes to CodeBox & Button component

* import KeyboardEvent & MouseEvent from react at Button index.file

* refactor: consolidate React imports into a single line

* refactor: consolidate React imports into a single line

* refactor: Button component & CodeBox compnent

* Update: Button component modified in case of type-saftey at some part

* omit unnecessary comment-lines, handle-proper naming

* omit unnecessary comment-lines, handle-proper naming

* Update apps/site/components/Common/Button/index.tsx

Signed-off-by: Claudio W <[email protected]>

---------

Signed-off-by: Claudio W <[email protected]>
Co-authored-by: Claudio W <[email protected]>
  • Loading branch information
faridomarAf and ovflowd authored Dec 16, 2024
1 parent d572121 commit 3c274ba
Showing 1 changed file with 50 additions and 13 deletions.
63 changes: 50 additions & 13 deletions apps/site/components/Common/Button/index.tsx
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;

0 comments on commit 3c274ba

Please sign in to comment.