import { h, Component } from 'preact';
function hyphenate(text) {
if (text.replace) {
return text.replace(/\s/g, '-');
}
return '';
}
const ID_PREFIX = 'tab-panel-';
export function TabPanel({ label }) {
return (
{this.props.children}
);
}
function Tab({ label, isSelected, onKeyUp, onClick }) {
return (
);
}
export default class Tabs extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 0
};
this.switchTab = this.switchTab.bind(this);
}
isSelected(index) {
return this.state.selectedTab === index;
}
switchTab(selectedTab) {
this.setState({ selectedTab: selectedTab });
this.tabListEl.querySelectorAll('[role=tab]')[selectedTab].focus();
if (this.props.onChange) {
this.props.onChange(this.state.selectedTab);
}
}
keyUpHandler(e) {
let { selectedTab } = this.state;
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
selectedTab--;
selectedTab =
selectedTab < 0 ? this.props.children.length - 1 : selectedTab;
this.switchTab(selectedTab);
e.preventDefault();
} else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
selectedTab++;
selectedTab %= this.props.children.length;
this.switchTab(selectedTab);
e.preventDefault();
}
}
render() {
const tabs = this.props.children;
return (
(this.tabListEl = el)}
>
{tabs.map((child, index) => (
this.switchTab(index)}
/>
))}
{tabs.map((child, index) =>
this.state.selectedTab === index ? child : null
)}
);
}
}