File size: 2,401 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React, { useEffect, useRef, useState } from 'react';
import { cx } from '../../cx';

import './Tabs.css';

export type TabProps = {
  children: React.ReactNode;
  title: string;
};

const getTabId = (index: number, suffix?: string) =>
  [`tab-${index}`, suffix].filter(Boolean).join('-');

export function Tabs({ children }) {
  const firstRender = useRef(true);
  const [currentTab, setCurrentTab] = useState(0);
  const tabsRefs = useRef<HTMLElement[]>([]);

  useEffect(() => {
    if (!firstRender.current && tabsRefs.current) {
      tabsRefs.current[currentTab].focus();
    }
  }, [currentTab]);

  useEffect(() => {
    firstRender.current = false;
  }, []);

  const onKeyDown = ({ key }: React.KeyboardEvent) => {
    if (key === 'ArrowLeft') {
      setCurrentTab(Math.max(0, currentTab - 1));
    } else if (key === 'ArrowRight') {
      setCurrentTab(
        Math.min(currentTab + 1, React.Children.count(children) - 1)
      );
    }
  };

  return (
    <div className="Tabs">
      <div role="tablist" className="Tabs-header">
        {React.Children.map<React.ReactChild, React.ReactElement<TabProps>>(
          children,
          (child, index) => {
            const isSelected = currentTab === index;
            return (
              <button
                role="tab"
                aria-selected={isSelected}
                aria-controls={getTabId(index, 'item')}
                id={getTabId(index, 'title')}
                tabIndex={isSelected ? 0 : -1}
                className={cx('Tabs-title', isSelected && 'Tabs-title--active')}
                ref={(element) => (tabsRefs.current[index] = element!)}
                key={getTabId(index)}
                onClick={() => setCurrentTab(index)}
                onKeyDown={onKeyDown}
              >
                {child.props.title}
              </button>
            );
          }
        )}
      </div>
      <div className="Tabs-list">
        {React.Children.map(children, (child, index) => (
          <div
            tabIndex={0}
            role="tabpanel"
            id={getTabId(index, 'item')}
            aria-labelledby={getTabId(index, 'title')}
            hidden={currentTab !== index}
            key={getTabId(index)}
          >
            {child}
          </div>
        ))}
      </div>
    </div>
  );
}

export function Tab({ children }: TabProps) {
  return <>{children}</>;
}