UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

228 lines 12.7 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; /** * * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { useMergeRefs } from '@floating-ui/react'; import classNames from 'classnames'; import React, { useCallback, useContext, useEffect, useRef, useState, } from 'react'; import { ArrowLeftCircleIconOutline, ArrowRightCircleIconOutline, } from '../icons'; import { Tooltip } from '../tooltip'; import { Typography } from '../typography'; import { useTabsScrollOverflow } from './use-tabs-scroll-overflow'; // Reusable scroll button component const ScrollButton = ({ direction, isVisible, onClick, onBackground, }) => { const Icon = direction === 'left' ? ArrowLeftCircleIconOutline : ArrowRightCircleIconOutline; const positionClass = direction === 'left' ? 'ndl-scroll-left-item' : 'ndl-scroll-right-item'; return (_jsx("div", { className: classNames('ndl-scroll-item', positionClass, { 'ndl-scroll-item-hidden': !isVisible, 'ndl-scroll-item-on-background-default': onBackground === 'default', 'ndl-scroll-item-on-background-weak': onBackground === 'weak', }), children: _jsx("button", { tabIndex: -1, className: "ndl-scroll-icon-wrapper", onClick: onClick, "aria-hidden": "true", children: _jsx(Icon, { className: "ndl-scroll-icon" }) }) })); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const TabsContext = React.createContext(null); const useTabsContext = () => { const context = useContext(TabsContext); if (context === null) { throw new Error('Tab used without context'); } return context; }; const getTabPanelId = (tabId) => `tabpanel-${tabId}`; const getGeneralTabClasses = (size, fill) => { return { 'ndl-filled-tab': fill === 'filled', 'ndl-large': size === 'large', 'ndl-small': size === 'small', 'ndl-underline-tab': fill === 'underline', }; }; const TabsComponent = (_a) => { var { children, size = 'large', fill = 'underline', onChange, value, onBackground = 'weak', className, style, as, htmlAttributes, ref } = _a, restProps = __rest(_a, ["children", "size", "fill", "onChange", "value", "onBackground", "className", "style", "as", "htmlAttributes", "ref"]); const tabRefs = useRef(new Map()); const containerRef = useRef(null); const scrollContainerRef = useRef(null); const mergedRef = useMergeRefs([containerRef, ref]); const [firstTabId, setFirstTabId] = useState(null); const [isValuePresent, setIsValuePresent] = useState(false); const valueRef = useRef(value); // Use the custom hook for scroll overflow behavior const { scrollState, scrollToNextItem, checkOverflow } = useTabsScrollOverflow(scrollContainerRef); useEffect(() => { valueRef.current = value; setIsValuePresent(tabRefs.current.has(value)); }, [value]); const registerTab = useCallback((tabId, tabRef) => { var _a; tabRefs.current.set(tabId, tabRef); const first = (_a = tabRefs.current.keys().next().value) !== null && _a !== void 0 ? _a : null; setFirstTabId((prev) => (prev === first ? prev : first)); if (tabId === valueRef.current) { setIsValuePresent(true); } }, []); const unregisterTab = useCallback((tabId) => { var _a; tabRefs.current.delete(tabId); const first = (_a = tabRefs.current.keys().next().value) !== null && _a !== void 0 ? _a : null; setFirstTabId((prev) => (prev === first ? prev : first)); if (tabId === valueRef.current) { setIsValuePresent(false); } }, []); // Check overflow when children change useEffect(() => { checkOverflow(); }, [checkOverflow, children]); const scrollTabIntoView = useCallback((tabId) => { const tabRef = tabRefs.current.get(tabId); const scrollContainer = scrollContainerRef.current; if ((tabRef === null || tabRef === void 0 ? void 0 : tabRef.current) && scrollContainer) { const tabRect = tabRef.current.getBoundingClientRect(); const containerRect = scrollContainer.getBoundingClientRect(); const containerCenter = containerRect.left + containerRect.width / 2; const targetScrollLeft = scrollContainer.scrollLeft + (tabRect.left - containerCenter + tabRect.width / 2); scrollContainer.scrollTo({ behavior: 'smooth', left: targetScrollLeft, }); } }, []); const handleKeyDown = useCallback((event) => { if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') { return; } event.preventDefault(); const tabIds = Array.from(tabRefs.current.keys()); const focusedElement = document.activeElement; // Find the currently focused tab let currentIndex = -1; for (let i = 0; i < tabIds.length; i++) { const tabRef = tabRefs.current.get(tabIds[i]); if ((tabRef === null || tabRef === void 0 ? void 0 : tabRef.current) === focusedElement) { currentIndex = i; break; } } // If no tab is focused, focus the active tab. Or the first tab if the active tab is not present. if (currentIndex === -1) { const activeTabRef = tabRefs.current.get(value); if (activeTabRef === null || activeTabRef === void 0 ? void 0 : activeTabRef.current) { activeTabRef.current.focus(); } else if (!isValuePresent && firstTabId !== null) { const firstTabRef = tabRefs.current.get(firstTabId); if (firstTabRef === null || firstTabRef === void 0 ? void 0 : firstTabRef.current) { firstTabRef.current.focus(); } } return; } let nextIndex; if (event.key === 'ArrowRight') { nextIndex = currentIndex === tabIds.length - 1 ? 0 : currentIndex + 1; } else { nextIndex = currentIndex === 0 ? tabIds.length - 1 : currentIndex - 1; } const nextTabId = tabIds[nextIndex]; const nextTabRef = tabRefs.current.get(nextTabId); if (nextTabRef === null || nextTabRef === void 0 ? void 0 : nextTabRef.current) { nextTabRef.current.focus(); scrollTabIntoView(nextTabId); } }, [value, scrollTabIntoView, firstTabId, isValuePresent]); const classes = classNames('ndl-tabs', getGeneralTabClasses(size, fill), className); const Component = as !== null && as !== void 0 ? as : 'div'; return (_jsxs(Component, Object.assign({ className: classes, style: style, role: "tablist", "aria-orientation": "horizontal", onKeyDown: handleKeyDown, ref: mergedRef }, restProps, htmlAttributes, { children: [_jsx(ScrollButton, { direction: "left", isVisible: scrollState.isLeftVisible, onClick: () => scrollToNextItem('left'), onBackground: onBackground }), _jsx(ScrollButton, { direction: "right", isVisible: scrollState.isRightVisible, onClick: () => scrollToNextItem('right'), onBackground: onBackground }), _jsx(TabsContext.Provider, { value: { fill, firstTabId, isValuePresent, onChange, registerTab, scrollTabIntoView, size, unregisterTab, value, }, children: _jsx("div", { className: "ndl-tabs-container", ref: scrollContainerRef, children: children }) })] }))); }; TabsComponent.displayName = 'Tabs'; const TabsTab = (_a) => { var { children, id: tabId, isDisabled = false, className, description, tooltipProps, style, as, htmlAttributes, ref } = _a, restProps = __rest(_a, ["children", "id", "isDisabled", "className", "description", "tooltipProps", "style", "as", "htmlAttributes", "ref"]); const { size, fill, value, onChange, registerTab, unregisterTab, scrollTabIntoView, firstTabId, isValuePresent, } = useTabsContext(); const internalRef = useRef(null); // Create a merged ref that handles both ref objects and ref functions const mergedRef = useMergeRefs([ internalRef, ref, ]); // Register/unregister tab for keyboard navigation useEffect(() => { registerTab(tabId, internalRef); return () => { unregisterTab(tabId); }; }, [tabId, registerTab, unregisterTab]); const baseClasses = classNames(Object.assign(Object.assign({}, getGeneralTabClasses(size, fill)), { 'ndl-disabled': isDisabled, 'ndl-selected': value === tabId })); const Component = as !== null && as !== void 0 ? as : 'button'; const classes = classNames('ndl-tab', baseClasses, className); // Only the active tab should be in the tab sequence initially // Other tabs can be focused via arrow keys but are not in tab sequence const tabIndex = value === tabId || (!isValuePresent && tabId === firstTabId) ? 0 : -1; return (_jsxs(Tooltip, Object.assign({ type: "simple" }, tooltipProps === null || tooltipProps === void 0 ? void 0 : tooltipProps.root, { isDisabled: description === undefined, children: [_jsx(Tooltip.Trigger, Object.assign({}, tooltipProps === null || tooltipProps === void 0 ? void 0 : tooltipProps.trigger, { hasButtonWrapper: true, children: _jsxs(Component, Object.assign({ className: classes, style: style, onClick: () => { if (!isDisabled) { onChange(tabId); scrollTabIntoView(tabId); } }, role: "tab", id: tabId, "aria-disabled": isDisabled, "aria-label": description, "aria-selected": value === tabId, "aria-controls": getTabPanelId(tabId), tabIndex: tabIndex, ref: mergedRef }, restProps, htmlAttributes, { children: [children, fill === 'underline' && _jsx("span", { className: "ndl-tab-underline" })] })) })), _jsx(Tooltip.Content, Object.assign({}, tooltipProps === null || tooltipProps === void 0 ? void 0 : tooltipProps.content, { children: description }))] }))); }; TabsTab.displayName = 'Tabs.Tab'; const TabsTabPanel = (_a) => { var { as, children, value, tabId, style, className, htmlAttributes, ref } = _a, restProps = __rest(_a, ["as", "children", "value", "tabId", "style", "className", "htmlAttributes", "ref"]); const Component = as !== null && as !== void 0 ? as : 'div'; return (_jsx(_Fragment, { children: value === tabId ? (_jsx(Component, Object.assign({ role: "tabpanel", id: getTabPanelId(tabId), "aria-labelledby": tabId, style: style, className: classNames(className), ref: ref }, restProps, htmlAttributes, { children: children }))) : null })); }; TabsTabPanel.displayName = 'Tabs.TabPanel'; const TabBadge = (_a) => { var { children, ref, htmlAttributes, style, className } = _a, restProps = __rest(_a, ["children", "ref", "htmlAttributes", "style", "className"]); const classes = classNames('ndl-tab-badge', className); return (_jsx(Typography, Object.assign({ ref: ref, variant: "subheading-small", className: classes, style: style, htmlAttributes: htmlAttributes }, restProps, { children: children }))); }; const Tabs = Object.assign(TabsComponent, { Badge: TabBadge, Tab: TabsTab, TabPanel: TabsTabPanel, }); export { Tabs }; //# sourceMappingURL=Tabs.js.map