Skip to content

Commit

Permalink
feat(tabs): traverse tabs with arrow keys
Browse files Browse the repository at this point in the history
  • Loading branch information
weronikaolejniczak committed Nov 8, 2024
1 parent b937ece commit 2f659a3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/eui/src/components/tabs/tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const EuiTab: FunctionComponent<Props> = ({
<a
role="tab"
aria-selected={!!isSelected}
tabIndex={isSelected ? 0 : -1}
className={classes}
css={cssTabStyles}
href={href}
Expand All @@ -123,6 +124,7 @@ export const EuiTab: FunctionComponent<Props> = ({
<button
role="tab"
aria-selected={!!isSelected}
tabIndex={isSelected ? 0 : -1}
type="button"
className={classes}
css={cssTabStyles}
Expand Down
24 changes: 23 additions & 1 deletion packages/eui/src/components/tabs/tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
import React, {
forwardRef,
HTMLAttributes,
KeyboardEventHandler,
PropsWithChildren,
ReactNode,
} from 'react';
import classNames from 'classnames';
import { useEuiMemoizedStyles } from '../../services';
import { keys, useEuiMemoizedStyles } from '../../services';
import { CommonProps } from '../common';
import { euiTabsStyles } from './tabs.styles';
import { EuiTabsContext } from './tabs_context';
Expand Down Expand Up @@ -67,11 +68,32 @@ export const EuiTabs = forwardRef<EuiTabRef, EuiTabsProps>(
bottomBorder && styles.bottomBorder,
];

const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
const tablist = event.currentTarget;
const tabs = tablist?.querySelectorAll<HTMLButtonElement>(
'[role="tab"]:not(:disabled, [inert])'
);
if (!tabs?.length) return;

const currentIndex = Array.from(tabs).findIndex((tab) =>
tab.matches(':focus')
);

if (event.key === keys.ARROW_LEFT) {
const previousIndex = (currentIndex - 1 + tabs.length) % tabs.length;
tabs[previousIndex].focus();
} else if (event.key === keys.ARROW_RIGHT) {
const nextIndex = (currentIndex + 1) % tabs.length;
tabs[nextIndex].focus();
}
};

return (
<div
ref={ref}
className={classes}
css={cssStyles}
onKeyDown={handleKeyDown}
{...(children && { role: 'tablist' })}
{...rest}
>
Expand Down

0 comments on commit 2f659a3

Please sign in to comment.