Debian Codegraph @

node/@patternfly/react-core/dist/esm/components/Tabs/Tabs.js

raw
1 import { __rest } from "tslib";
2 import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3 import { Children, Component, createRef, isValidElement } from 'react';
4 import styles from '@patternfly/react-styles/css/components/Tabs/tabs.mjs';
5 import { css } from '@patternfly/react-styles';
6 import RhMicronsCaretLeftIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-left-icon';
7 import RhMicronsCaretRightIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-right-icon';
8 import RhMicronsCaretDownIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-down-icon';
9 import PlusIcon from '@patternfly/react-icons/dist/esm/icons/plus-icon';
10 import { isElementInView, formatBreakpointMods, getLanguageDirection, getInlineStartProperty } from '../../helpers/util';
11 import { TabContent } from './TabContent';
12 import { TabsContextProvider } from './TabsContext';
13 import { OverflowTab } from './OverflowTab';
14 import { Button } from '../Button';
15 import { getOUIAProps, canUseDOM } from '../../helpers';
16 import { SSRSafeIds } from '../../helpers/SSRSafeIds/SSRSafeIds';
17 import { GenerateId } from '../../helpers/GenerateId/GenerateId';
18 import linkAccentLength from '@patternfly/react-tokens/dist/esm/c_tabs_link_accent_length';
19 import linkAccentStart from '@patternfly/react-tokens/dist/esm/c_tabs_link_accent_start';
20 export var TabsComponent;
21 (function (TabsComponent) {
22 TabsComponent["div"] = "div";
23 TabsComponent["nav"] = "nav";
24 })(TabsComponent || (TabsComponent = {}));
25 const variantStyle = {
26 default: '',
27 secondary: styles.modifiers.secondary
28 };
29 class Tabs extends Component {
30 constructor(props) {
31 super(props);
32 this.tabList = createRef();
33 this.leftScrollButtonRef = createRef();
34 this.direction = 'ltr';
35 this.scrollTimeout = null;
36 this.countOverflowingElements = (container) => {
37 const elements = Array.from(container.children);
38 return elements.filter((element) => !isElementInView(container, element, false)).length;
39 };
40 this.handleScrollButtons = () => {
41 const { isOverflowHorizontal: isOverflowHorizontal } = this.props;
42 // add debounce to the scroll event
43 clearTimeout(this.scrollTimeout);
44 this.scrollTimeout = setTimeout(() => {
45 const container = this.tabList.current;
46 let disableBackScrollButton = true;
47 let disableForwardScrollButton = true;
48 let enableScrollButtons = false;
49 let overflowingTabCount = 0;
50 if (container && !this.props.isVertical && !isOverflowHorizontal) {
51 // get first element and check if it is in view
52 const overflowOnLeft = !isElementInView(container, container.firstChild, false);
53 // get last element and check if it is in view
54 const overflowOnRight = !isElementInView(container, container.lastChild, false);
55 enableScrollButtons = overflowOnLeft || overflowOnRight;
56 disableBackScrollButton = !overflowOnLeft;
57 disableForwardScrollButton = !overflowOnRight;
58 }
59 if (isOverflowHorizontal) {
60 overflowingTabCount = this.countOverflowingElements(container);
61 }
62 this.setState({
63 enableScrollButtons,
64 disableBackScrollButton,
65 disableForwardScrollButton,
66 overflowingTabCount
67 });
68 }, 100);
69 };
70 this.scrollBack = () => {
71 // find first Element that is fully in view on the left, then scroll to the element before it
72 if (this.tabList.current) {
73 const container = this.tabList.current;
74 const childrenArr = Array.from(container.children);
75 let firstElementInView;
76 let lastElementOutOfView;
77 let i;
78 for (i = 0; i < childrenArr.length && !firstElementInView; i++) {
79 if (isElementInView(container, childrenArr[i], false)) {
80 firstElementInView = childrenArr[i];
81 lastElementOutOfView = childrenArr[i - 1];
82 }
83 }
84 if (lastElementOutOfView) {
85 if (this.direction === 'ltr') {
86 // LTR scrolls left to go back
87 container.scrollLeft -= lastElementOutOfView.scrollWidth;
88 }
89 else {
90 // RTL scrolls right to go back
91 container.scrollLeft += lastElementOutOfView.scrollWidth;
92 }
93 }
94 }
95 };
96 this.scrollForward = () => {
97 // find last Element that is fully in view on the right, then scroll to the element after it
98 if (this.tabList.current) {
99 const container = this.tabList.current;
100 const childrenArr = Array.from(container.children);
101 let lastElementInView;
102 let firstElementOutOfView;
103 for (let i = childrenArr.length - 1; i >= 0 && !lastElementInView; i--) {
104 if (isElementInView(container, childrenArr[i], false)) {
105 lastElementInView = childrenArr[i];
106 firstElementOutOfView = childrenArr[i + 1];
107 }
108 }
109 if (firstElementOutOfView) {
110 if (this.direction === 'ltr') {
111 // LTR scrolls right to go forward
112 container.scrollLeft += firstElementOutOfView.scrollWidth;
113 }
114 else {
115 // RTL scrolls left to go forward
116 container.scrollLeft -= firstElementOutOfView.scrollWidth;
117 }
118 }
119 }
120 };
121 this.hideScrollButtons = () => {
122 const { enableScrollButtons, renderScrollButtons, showScrollButtons } = this.state;
123 if (!enableScrollButtons && !showScrollButtons && renderScrollButtons) {
124 this.setState({ renderScrollButtons: false });
125 }
126 };
127 this.setAccentStyles = (shouldInitializeStyle) => {
128 const currentItem = this.tabList.current.querySelector('li.pf-m-current');
129 if (!currentItem) {
130 return;
131 }
132 const { isVertical } = this.props;
133 const { offsetWidth, offsetHeight, offsetTop } = currentItem;
134 const lengthValue = isVertical ? offsetHeight : offsetWidth;
135 const startValue = isVertical ? offsetTop : getInlineStartProperty(currentItem, this.tabList.current);
136 this.setState(Object.assign({ currentLinkAccentLength: `${lengthValue}px`, currentLinkAccentStart: `${startValue}px` }, (shouldInitializeStyle && { isInitializingAccent: true })));
137 setTimeout(() => {
138 this.setState({ isInitializingAccent: false });
139 }, 0);
140 };
141 this.handleResize = () => {
142 this.handleScrollButtons();
143 this.setAccentStyles();
144 };
145 this.state = {
146 enableScrollButtons: false,
147 showScrollButtons: false,
148 renderScrollButtons: false,
149 disableBackScrollButton: true,
150 disableForwardScrollButton: true,
151 shownKeys: this.props.defaultActiveKey !== undefined ? [this.props.defaultActiveKey] : [this.props.activeKey], // only for mountOnEnter case
152 uncontrolledActiveKey: this.props.defaultActiveKey,
153 uncontrolledIsExpandedLocal: this.props.defaultIsExpanded,
154 overflowingTabCount: 0,
155 isInitializingAccent: true,
156 currentLinkAccentLength: linkAccentLength.value,
157 currentLinkAccentStart: linkAccentStart.value
158 };
159 if (this.props.isVertical && this.props.expandable !== undefined) {
160 if (!this.props.toggleAriaLabel && !this.props.toggleText) {
161 // eslint-disable-next-line no-console
162 console.error('Tabs:', 'toggleAriaLabel or the toggleText prop is required to make the toggle button accessible');
163 }
164 }
165 }
166 handleTabClick(event, eventKey, tabContentRef) {
167 const { shownKeys } = this.state;
168 const { onSelect, defaultActiveKey } = this.props;
169 // if defaultActiveKey Tabs are uncontrolled, set new active key internally
170 if (defaultActiveKey !== undefined) {
171 this.setState({
172 uncontrolledActiveKey: eventKey
173 });
174 }
175 else {
176 onSelect(event, eventKey);
177 }
178 // process any tab content sections outside of the component
179 if (tabContentRef) {
180 Children.toArray(this.props.children)
181 .filter((child) => isValidElement(child))
182 .filter(({ props }) => props.tabContentRef && props.tabContentRef.current)
183 .forEach((child) => (child.props.tabContentRef.current.hidden = true));
184 // most recently selected tabContent
185 if (tabContentRef.current) {
186 tabContentRef.current.hidden = false;
187 }
188 }
189 if (this.props.mountOnEnter) {
190 this.setState({
191 shownKeys: shownKeys.concat(eventKey)
192 });
193 }
194 }
195 componentDidMount() {
196 if (!this.props.isVertical) {
197 if (canUseDOM) {
198 window.addEventListener('resize', this.handleResize, false);
199 }
200 this.direction = getLanguageDirection(this.tabList.current);
201 // call the handle resize function to check if scroll buttons should be shown
202 this.handleScrollButtons();
203 }
204 this.setAccentStyles(true);
205 }
206 componentWillUnmount() {
207 var _a;
208 if (!this.props.isVertical) {
209 if (canUseDOM) {
210 window.removeEventListener('resize', this.handleResize, false);
211 }
212 }
213 clearTimeout(this.scrollTimeout);
214 (_a = this.leftScrollButtonRef.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('transitionend', this.hideScrollButtons);
215 }
216 componentDidUpdate(prevProps, prevState) {
217 this.direction = getLanguageDirection(this.tabList.current);
218 const { activeKey, mountOnEnter, isOverflowHorizontal, children, defaultActiveKey } = this.props;
219 const { shownKeys, overflowingTabCount, enableScrollButtons, uncontrolledActiveKey } = this.state;
220 const isOnCloseUpdate = !!prevProps.onClose !== !!this.props.onClose;
221 if ((defaultActiveKey !== undefined && prevState.uncontrolledActiveKey !== uncontrolledActiveKey) ||
222 (defaultActiveKey === undefined && prevProps.activeKey !== activeKey) ||
223 isOnCloseUpdate) {
224 this.setAccentStyles(isOnCloseUpdate);
225 }
226 if (prevProps.activeKey !== activeKey && mountOnEnter && shownKeys.indexOf(activeKey) < 0) {
227 this.setState({
228 shownKeys: shownKeys.concat(activeKey)
229 });
230 }
231 if (prevProps.children &&
232 children &&
233 Children.toArray(prevProps.children).length !== Children.toArray(children).length) {
234 this.handleScrollButtons();
235 this.setAccentStyles(true);
236 }
237 const currentOverflowingTabCount = this.countOverflowingElements(this.tabList.current);
238 if (isOverflowHorizontal && currentOverflowingTabCount) {
239 this.setState({ overflowingTabCount: currentOverflowingTabCount + overflowingTabCount });
240 }
241 if (!prevState.enableScrollButtons && enableScrollButtons) {
242 this.setState({ renderScrollButtons: true });
243 setTimeout(() => {
244 var _a, _b;
245 // Remove any existing listener before adding a new one to prevent accumulation
246 (_a = this.leftScrollButtonRef.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('transitionend', this.hideScrollButtons);
247 (_b = this.leftScrollButtonRef.current) === null || _b === void 0 ? void 0 : _b.addEventListener('transitionend', this.hideScrollButtons);
248 this.setState({ showScrollButtons: true });
249 }, 100);
250 }
251 else if (prevState.enableScrollButtons && !enableScrollButtons) {
252 this.setState({ showScrollButtons: false });
253 }
254 if (prevState.uncontrolledIsExpandedLocal !== this.state.uncontrolledIsExpandedLocal) {
255 this.setAccentStyles(true);
256 }
257 }
258 static getDerivedStateFromProps(nextProps, prevState) {
259 if (prevState.uncontrolledActiveKey === undefined) {
260 return null;
261 }
262 const childrenHasTabWithActiveEventKey = Children.toArray(nextProps.children)
263 .filter((child) => isValidElement(child))
264 .some(({ props }) => props.eventKey === prevState.uncontrolledActiveKey);
265 // if uncontrolledActiveKey is an existing eventKey of any Tab of nextProps.children --> don't update uncontrolledActiveKey
266 if (childrenHasTabWithActiveEventKey) {
267 return null;
268 }
269 // otherwise update state derived from nextProps.defaultActiveKey
270 return {
271 uncontrolledActiveKey: nextProps.defaultActiveKey,
272 shownKeys: nextProps.defaultActiveKey !== undefined ? [nextProps.defaultActiveKey] : [nextProps.activeKey] // only for mountOnEnter case
273 };
274 }
275 render() {
276 const _a = this.props, { className, children, activeKey, defaultActiveKey, id, isAddButtonDisabled, isFilled, isSubtab, isNav, isVertical, isBox, hasNoBorderBottom, leftScrollAriaLabel, rightScrollAriaLabel, backScrollAriaLabel, forwardScrollAriaLabel, 'aria-label': ariaLabel, component, ouiaId, ouiaSafe, mountOnEnter, unmountOnExit, usePageInsets, inset, variant, expandable, isExpanded, defaultIsExpanded, toggleText, toggleAriaLabel, addButtonAriaLabel, tabListAriaLabel, tabListAriaLabelledBy, onToggle, onClose, onAdd, isOverflowHorizontal: isOverflowHorizontal } = _a, props = __rest(_a, ["className", "children", "activeKey", "defaultActiveKey", "id", "isAddButtonDisabled", "isFilled", "isSubtab", "isNav", "isVertical", "isBox", "hasNoBorderBottom", "leftScrollAriaLabel", "rightScrollAriaLabel", "backScrollAriaLabel", "forwardScrollAriaLabel", 'aria-label', "component", "ouiaId", "ouiaSafe", "mountOnEnter", "unmountOnExit", "usePageInsets", "inset", "variant", "expandable", "isExpanded", "defaultIsExpanded", "toggleText", "toggleAriaLabel", "addButtonAriaLabel", "tabListAriaLabel", "tabListAriaLabelledBy", "onToggle", "onClose", "onAdd", "isOverflowHorizontal"]);
277 const { showScrollButtons, renderScrollButtons, disableBackScrollButton, disableForwardScrollButton, shownKeys, uncontrolledActiveKey, uncontrolledIsExpandedLocal, overflowingTabCount, isInitializingAccent, currentLinkAccentLength, currentLinkAccentStart } = this.state;
278 const filteredChildren = Children.toArray(children)
279 .filter((child) => isValidElement(child))
280 .filter(({ props }) => !props.isHidden);
281 const filteredChildrenWithoutOverflow = filteredChildren.slice(0, filteredChildren.length - overflowingTabCount);
282 const filteredChildrenOverflowing = filteredChildren.slice(filteredChildren.length - overflowingTabCount);
283 const overflowingTabProps = filteredChildrenOverflowing.map((child) => child.props);
284 const defaultComponent = isNav && !component ? 'nav' : 'div';
285 const Component = component !== undefined ? component : defaultComponent;
286 const localActiveKey = defaultActiveKey !== undefined ? uncontrolledActiveKey : activeKey;
287 const isExpandedLocal = defaultIsExpanded !== undefined ? uncontrolledIsExpandedLocal : isExpanded;
288 /* Uncontrolled expandable tabs */
289 const toggleTabs = (event, newValue) => {
290 if (isExpanded === undefined) {
291 this.setState({ uncontrolledIsExpandedLocal: newValue });
292 }
293 else {
294 onToggle(event, newValue);
295 }
296 };
297 const hasOverflowTab = isOverflowHorizontal && overflowingTabCount > 0;
298 const overflowObjectProps = typeof isOverflowHorizontal === 'object' ? Object.assign({}, isOverflowHorizontal) : {};
299 return (_jsx(SSRSafeIds, { prefix: "pf-random-id-", ouiaComponentType: Tabs.displayName, children: (generatedId, generatedOuiaId) => {
300 const uniqueId = id || generatedId;
301 return (_jsxs(TabsContextProvider, { value: {
302 variant,
303 mountOnEnter,
304 unmountOnExit,
305 localActiveKey,
306 uniqueId,
307 setAccentStyles: this.setAccentStyles,
308 handleTabClick: (...args) => this.handleTabClick(...args),
309 handleTabClose: onClose
310 }, children: [_jsxs(Component, Object.assign({ "aria-label": ariaLabel, className: css(styles.tabs, styles.modifiers.animateCurrent, isFilled && styles.modifiers.fill, isSubtab && styles.modifiers.subtab, isNav && styles.modifiers.nav, isVertical && styles.modifiers.vertical, isVertical && expandable && formatBreakpointMods(expandable, styles), isVertical && expandable && isExpandedLocal && styles.modifiers.expanded, isBox && styles.modifiers.box, showScrollButtons && styles.modifiers.scrollable, usePageInsets && styles.modifiers.pageInsets, hasNoBorderBottom && styles.modifiers.noBorderBottom, formatBreakpointMods(inset, styles), variantStyle[variant], hasOverflowTab && styles.modifiers.overflow, isInitializingAccent && styles.modifiers.initializingAccent, className) }, getOUIAProps(Tabs.displayName, ouiaId !== undefined ? ouiaId : generatedOuiaId, ouiaSafe), { id: id && id }, props, { style: Object.assign({ [linkAccentLength.name]: currentLinkAccentLength, [linkAccentStart.name]: currentLinkAccentStart }, props.style), children: [expandable && isVertical && (_jsx(GenerateId, { children: (randomId) => (_jsx("div", { className: css(styles.tabsToggle), children: _jsx("div", { className: 'pf-v6-c-tabs__toggle-button', children: _jsx(Button, { onClick: (event) => toggleTabs(event, !isExpandedLocal), variant: "plain", "aria-label": toggleAriaLabel, "aria-expanded": isExpandedLocal, id: `${randomId}-button`, "aria-labelledby": `${randomId}-text ${randomId}-button`, icon: _jsx("span", { className: css(styles.tabsToggleIcon), children: _jsx(RhMicronsCaretDownIcon, {}) }), children: toggleText && _jsx("span", { id: `${randomId}-text`, children: toggleText }) }) }) })) })), renderScrollButtons && (_jsx("div", { className: css(styles.tabsScrollButton), children: _jsx(Button, { "aria-label": backScrollAriaLabel || leftScrollAriaLabel, onClick: this.scrollBack, isDisabled: disableBackScrollButton, "aria-hidden": disableBackScrollButton, ref: this.leftScrollButtonRef, variant: "plain", icon: _jsx(RhMicronsCaretLeftIcon, {}) }) })), _jsxs("ul", { "aria-label": tabListAriaLabel, "aria-labelledby": tabListAriaLabelledBy, className: css(styles.tabsList), ref: this.tabList, onScroll: this.handleScrollButtons, role: "tablist", children: [isOverflowHorizontal ? filteredChildrenWithoutOverflow : filteredChildren, hasOverflowTab && _jsx(OverflowTab, Object.assign({ overflowingTabs: overflowingTabProps }, overflowObjectProps))] }), renderScrollButtons && (_jsx("div", { className: css(styles.tabsScrollButton), children: _jsx(Button, { "aria-label": forwardScrollAriaLabel || rightScrollAriaLabel, onClick: this.scrollForward, isDisabled: disableForwardScrollButton, "aria-hidden": disableForwardScrollButton, variant: "plain", icon: _jsx(RhMicronsCaretRightIcon, {}) }) })), onAdd !== undefined && (_jsx("span", { className: css(styles.tabsAdd), children: _jsx(Button, { variant: "plain", "aria-label": addButtonAriaLabel || 'Add tab', onClick: onAdd, icon: _jsx(PlusIcon, {}), isDisabled: isAddButtonDisabled }) }))] })), filteredChildren
311 .filter((child) => child.props.children &&
312 !(unmountOnExit && child.props.eventKey !== localActiveKey) &&
313 !(mountOnEnter && shownKeys.indexOf(child.props.eventKey) === -1))
314 .map((child) => (_jsx(TabContent, { activeKey: localActiveKey, child: child, id: child.props.id || uniqueId, ouiaId: child.props.ouiaId }, child.props.eventKey)))] }));
315 } }));
316 }
317 }
318 Tabs.displayName = 'Tabs';
319 Tabs.defaultProps = {
320 activeKey: 0,
321 onSelect: () => undefined,
322 isFilled: false,
323 isSubtab: false,
324 isNav: false,
325 isVertical: false,
326 isBox: false,
327 hasNoBorderBottom: false,
328 leftScrollAriaLabel: 'Scroll left',
329 backScrollAriaLabel: 'Scroll back',
330 rightScrollAriaLabel: 'Scroll right',
331 forwardScrollAriaLabel: 'Scroll forward',
332 mountOnEnter: false,
333 unmountOnExit: false,
334 ouiaSafe: true,
335 variant: 'default',
336 onToggle: (_event, _isExpanded) => undefined
337 };
338 export { Tabs };
339 //# sourceMappingURL=Tabs.js.map