Skip to content

Commit

Permalink
refactor(v2): make better a11y for tabs (#1990)
Browse files Browse the repository at this point in the history
* refactor(v2): make better a11y for tabs

* Update styles.module.css
  • Loading branch information
lex111 authored and yangshun committed Nov 24, 2019
1 parent 3aa2ab6 commit 3265dda
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
53 changes: 51 additions & 2 deletions packages/docusaurus-theme-classic/src/theme/Tabs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,77 @@ import React, {useState, Children} from 'react';

import classnames from 'classnames';

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

const keys = {
left: 37,
right: 39,
};

function Tabs(props) {
const {block, children, defaultValue, values} = props;
const [selectedValue, setSelectedValue] = useState(defaultValue);
const tabRefs = [];

const focusNextTab = (tabs, target) => {
const next = tabs.indexOf(target) + 1;

if (!tabs[next]) {
tabs[0].focus();
} else {
tabs[next].focus();
}
};

const focusPreviousTab = (tabs, target) => {
const prev = tabs.indexOf(target) - 1;

if (!tabs[prev]) {
tabs[tabs.length - 1].focus();
} else {
tabs[prev].focus();
}
};

const handleKeydown = (tabs, target, event) => {
switch (event.keyCode) {
case keys.right:
focusNextTab(tabs, target);
break;
case keys.left:
focusPreviousTab(tabs, target);
break;
default:
break;
}
};

return (
<div>
<ul
role="tablist"
aria-orientation="horizontal"
className={classnames('tabs', {
'tabs--block': block,
})}>
{values.map(({value, label}) => (
<li
className={classnames('tab-item', {
role="tab"
tabIndex="0"
aria-selected={selectedValue === value}
className={classnames('tab-item', styles.tabItem, {
'tab-item--active': selectedValue === value,
})}
key={value}
ref={tabControl => tabRefs.push(tabControl)}
onKeyDown={event => handleKeydown(tabRefs, event.target, event)}
onFocus={() => setSelectedValue(value)}
onClick={() => setSelectedValue(value)}>
{label}
</li>
))}
</ul>
<div className="margin-vert--md">
<div role="tabpanel" className="margin-vert--md">
{
Children.toArray(children).filter(
child => child.props.value === selectedValue,
Expand Down
10 changes: 10 additions & 0 deletions packages/docusaurus-theme-classic/src/theme/Tabs/styles.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

.tabItem:focus {
background-color: var(--ifm-hover-overlay);
}

0 comments on commit 3265dda

Please sign in to comment.