Debian Codegraph @

node/@patternfly/react-core/src/components/Tabs/examples/TabsDynamic.tsx

raw
1 import { useEffect, useRef, useState } from 'react';
2 import { Tabs, Tab, TabTitleText } from '@patternfly/react-core';
3
4 export const TabsDynamic: React.FunctionComponent = () => {
5 const [activeTabKey, setActiveTabKey] = useState<number>(0);
6 const [tabs, setTabs] = useState<string[]>(['Terminal 1', 'Terminal 2', 'Terminal 3']);
7 const [newTabNumber, setNewTabNumber] = useState<number>(4);
8 const tabComponentRef = useRef<any>(undefined);
9 const firstMount = useRef(true);
10
11 const onClose = (event: any, tabIndex: string | number) => {
12 const tabIndexNum = tabIndex as number;
13 let nextTabIndex = activeTabKey;
14 if (tabIndexNum < activeTabKey) {
15 // if a preceding tab is closing, keep focus on the new index of the current tab
16 nextTabIndex = activeTabKey - 1 > 0 ? activeTabKey - 1 : 0;
17 } else if (activeTabKey === tabs.length - 1) {
18 // if the closing tab is the last tab, focus the preceding tab
19 nextTabIndex = tabs.length - 2 > 0 ? tabs.length - 2 : 0;
20 }
21 setActiveTabKey(nextTabIndex);
22 setTabs(tabs.filter((tab, index) => index !== tabIndex));
23 };
24
25 const onAdd = () => {
26 setTabs([...tabs, `Terminal ${newTabNumber}`]);
27 setActiveTabKey(tabs.length);
28 setNewTabNumber(newTabNumber + 1);
29 };
30
31 useEffect(() => {
32 if (firstMount.current) {
33 firstMount.current = false;
34 return;
35 } else {
36 const first = tabComponentRef.current.tabList.current.childNodes[activeTabKey];
37 first && first.firstChild.focus();
38 }
39 }, [tabs]);
40
41 return (
42 <Tabs
43 activeKey={activeTabKey}
44 onSelect={(event: any, tabIndex: string | number) => setActiveTabKey(tabIndex as number)}
45 onClose={onClose}
46 onAdd={onAdd}
47 aria-label="Tabs in the addable/closeable example"
48 addButtonAriaLabel="Add new tab"
49 role="region"
50 ref={tabComponentRef}
51 >
52 {tabs.map((tab, index) => (
53 <Tab
54 key={index}
55 eventKey={index}
56 aria-label={`Dynamic ${tab}`}
57 title={<TabTitleText>{tab}</TabTitleText>}
58 closeButtonAriaLabel={`Close ${tab}`}
59 isCloseDisabled={tabs.length === 1}
60 >
61 {tab}
62 </Tab>
63 ))}
64 </Tabs>
65 );
66 };