UNPKG

@primer/react

Version:

An implementation of GitHub's Primer Design System using React

181 lines (175 loc) • 7.79 kB
import React, { useState, useRef, useEffect, Children, isValidElement, cloneElement } from 'react'; import { TabContainerElement } from '@github/tab-container-element'; import { createComponent } from '../../utils/create-component.js'; import { StyledUnderlineWrapper, StyledUnderlineItemList, UnderlineItem } from '../../internal/components/UnderlineTabbedInterface.js'; import Box from '../../Box/Box.js'; import '@primer/behaviors/utils'; import '@primer/behaviors'; import { useResizeObserver } from '../../hooks/useResizeObserver.js'; import useIsomorphicLayoutEffect from '../../utils/useIsomorphicLayoutEffect.js'; import { useId } from '../../hooks/useId.js'; import { invariant } from '../../utils/invariant.js'; import '@styled-system/css'; import merge from 'deepmerge'; import { defaultSxProp } from '../../utils/defaultSxProp.js'; import '../../FeatureFlags/FeatureFlags.js'; import { useFeatureFlag } from '../../FeatureFlags/useFeatureFlag.js'; import '../../FeatureFlags/DefaultFeatureFlags.js'; import classes from './UnderlinePanels.module.css.js'; import { toggleStyledComponent } from '../../internal/utils/toggleStyledComponent.js'; import { clsx } from 'clsx'; function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } const CSS_MODULES_FEATURE_FLAG = 'primer_react_css_modules_staff'; const TabContainerComponent = createComponent(TabContainerElement, 'tab-container'); const StyledTabContainerComponent = toggleStyledComponent(CSS_MODULES_FEATURE_FLAG, 'tab-container', TabContainerComponent); const UnderlinePanels = ({ 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, children, loadingCounters, sx: sxProp = defaultSxProp, className, ...props }) => { const [iconsVisible, setIconsVisible] = useState(true); const wrapperRef = useRef(null); const listRef = useRef(null); // We need to always call useId() because React Hooks must be // called in the exact same order in every component render const parentId = useId(props.id); const [tabs, setTabs] = useState([]); const [tabPanels, setTabPanels] = useState([]); // Make sure we have fresh prop data whenever the tabs or panels are updated (keep aria-selected current) useEffect(() => { // Loop through the chidren, if it's a tab, then add id="{id}-tab-{index}" // If it's a panel, then add aria-labelledby="{id}-tab-{index}" let tabIndex = 0; let panelIndex = 0; const childrenWithProps = Children.map(children, child => { if (/*#__PURE__*/isValidElement(child) && child.type === Tab) { return /*#__PURE__*/cloneElement(child, { id: `${parentId}-tab-${tabIndex++}`, loadingCounters, iconsVisible }); } if (/*#__PURE__*/isValidElement(child) && child.type === Panel) { return /*#__PURE__*/cloneElement(child, { 'aria-labelledby': `${parentId}-tab-${panelIndex++}` }); } return child; }); const newTabs = Children.toArray(childrenWithProps).filter(child => { return /*#__PURE__*/isValidElement(child) && child.type === Tab; }); const newTabPanels = Children.toArray(childrenWithProps).filter(child => /*#__PURE__*/isValidElement(child) && child.type === Panel); setTabs(newTabs); setTabPanels(newTabPanels); }, [children, parentId, loadingCounters, iconsVisible]); const tabsHaveIcons = tabs.some(tab => /*#__PURE__*/React.isValidElement(tab) && tab.props.icon); const enabled = useFeatureFlag(CSS_MODULES_FEATURE_FLAG); // this is a workaround to get the list's width on the first render const [listWidth, setListWidth] = useState(0); useIsomorphicLayoutEffect(() => { var _listRef$current$getB, _listRef$current; if (!tabsHaveIcons) { return; } setListWidth((_listRef$current$getB = (_listRef$current = listRef.current) === null || _listRef$current === undefined ? undefined : _listRef$current.getBoundingClientRect().width) !== null && _listRef$current$getB !== undefined ? _listRef$current$getB : 0); }, [tabsHaveIcons]); // when the wrapper resizes, check if the icons should be visible // by comparing the wrapper width to the list width useResizeObserver(resizeObserverEntries => { if (!tabsHaveIcons) { return; } const wrapperWidth = resizeObserverEntries[0].contentRect.width; setIconsVisible(wrapperWidth > listWidth); }, wrapperRef, [enabled]); if (process.env.NODE_ENV !== "production") { const selectedTabs = tabs.filter(tab => { const ariaSelected = /*#__PURE__*/React.isValidElement(tab) && tab.props['aria-selected']; return ariaSelected === true || ariaSelected === 'true'; }); !(selectedTabs.length <= 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Only one tab can be selected at a time.') : invariant(false) : undefined; !(tabs.length === tabPanels.length) ? process.env.NODE_ENV !== "production" ? invariant(false, `The number of tabs and panels must be equal. Counted ${tabs.length} tabs and ${tabPanels.length} panels.`) : invariant(false) : undefined; } if (enabled) { return /*#__PURE__*/React.createElement(StyledTabContainerComponent, null, /*#__PURE__*/React.createElement(StyledUnderlineWrapper, _extends({ ref: wrapperRef, slot: "tablist-wrapper", "data-icons-visible": iconsVisible, sx: sxProp, className: clsx(className, classes.StyledUnderlineWrapper) }, props), /*#__PURE__*/React.createElement(StyledUnderlineItemList, { ref: listRef, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, role: "tablist" }, tabs)), tabPanels); } return /*#__PURE__*/React.createElement(StyledTabContainerComponent, null, /*#__PURE__*/React.createElement(StyledUnderlineWrapper, _extends({ ref: wrapperRef, slot: "tablist-wrapper", "data-icons-visible": iconsVisible, sx: merge({ width: '100%', overflowX: 'auto', overflowY: 'hidden', '-webkit-overflow-scrolling': 'auto', '&[data-icons-visible="false"] [data-component="icon"]': { display: 'none' } }, sxProp), className: className }, props), /*#__PURE__*/React.createElement(StyledUnderlineItemList, { ref: listRef, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, role: "tablist" }, tabs)), tabPanels); }; UnderlinePanels.displayName = "UnderlinePanels"; const Tab = ({ 'aria-selected': ariaSelected, sx: sxProp = defaultSxProp, onSelect, ...props }) => { const clickHandler = React.useCallback(event => { if (!event.defaultPrevented && typeof onSelect === 'function') { onSelect(event); } }, [onSelect]); const keyDownHandler = React.useCallback(event => { if ((event.key === ' ' || event.key === 'Enter') && !event.defaultPrevented && typeof onSelect === 'function') { onSelect(event); } }, [onSelect]); return /*#__PURE__*/React.createElement(UnderlineItem, _extends({ as: "button", role: "tab", tabIndex: ariaSelected ? 0 : -1, "aria-selected": ariaSelected, sx: sxProp, type: "button", onClick: clickHandler, onKeyDown: keyDownHandler }, props)); }; Tab.displayName = "Tab"; Tab.displayName = 'UnderlinePanels.Tab'; const Panel = props => { return /*#__PURE__*/React.createElement(Box, _extends({ as: "div", role: "tabpanel" }, props)); }; Panel.displayName = "Panel"; Panel.displayName = 'UnderlinePanels.Panel'; var UnderlinePanels$1 = Object.assign(UnderlinePanels, { Panel, Tab }); export { UnderlinePanels$1 as default };