Debian Codegraph @

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

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