@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
267 lines • 14.9 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tabs = void 0;
const jsx_runtime_1 = require("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/>.
*/
const react_1 = require("@floating-ui/react");
const classnames_1 = __importDefault(require("classnames"));
const react_2 = __importStar(require("react"));
const icons_1 = require("../icons");
const tooltip_1 = require("../tooltip");
const typography_1 = require("../typography");
const use_tabs_scroll_overflow_1 = require("./use-tabs-scroll-overflow");
// Reusable scroll button component
const ScrollButton = ({ direction, isVisible, onClick, onBackground, }) => {
const Icon = direction === 'left'
? icons_1.ArrowLeftCircleIconOutline
: icons_1.ArrowRightCircleIconOutline;
const positionClass = direction === 'left' ? 'ndl-scroll-left-item' : 'ndl-scroll-right-item';
return ((0, jsx_runtime_1.jsx)("div", { className: (0, classnames_1.default)('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: (0, jsx_runtime_1.jsx)("button", { tabIndex: -1, className: "ndl-scroll-icon-wrapper", onClick: onClick, "aria-hidden": "true", children: (0, jsx_runtime_1.jsx)(Icon, { className: "ndl-scroll-icon" }) }) }));
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const TabsContext = react_2.default.createContext(null);
const useTabsContext = () => {
const context = (0, react_2.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 = (0, react_2.useRef)(new Map());
const containerRef = (0, react_2.useRef)(null);
const scrollContainerRef = (0, react_2.useRef)(null);
const mergedRef = (0, react_1.useMergeRefs)([containerRef, ref]);
const [firstTabId, setFirstTabId] = (0, react_2.useState)(null);
const [isValuePresent, setIsValuePresent] = (0, react_2.useState)(false);
const valueRef = (0, react_2.useRef)(value);
// Use the custom hook for scroll overflow behavior
const { scrollState, scrollToNextItem, checkOverflow } = (0, use_tabs_scroll_overflow_1.useTabsScrollOverflow)(scrollContainerRef);
(0, react_2.useEffect)(() => {
valueRef.current = value;
setIsValuePresent(tabRefs.current.has(value));
}, [value]);
const registerTab = (0, react_2.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 = (0, react_2.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
(0, react_2.useEffect)(() => {
checkOverflow();
}, [checkOverflow, children]);
const scrollTabIntoView = (0, react_2.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 = (0, react_2.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 = (0, classnames_1.default)('ndl-tabs', getGeneralTabClasses(size, fill), className);
const Component = as !== null && as !== void 0 ? as : 'div';
return ((0, jsx_runtime_1.jsxs)(Component, Object.assign({ className: classes, style: style, role: "tablist", "aria-orientation": "horizontal", onKeyDown: handleKeyDown, ref: mergedRef }, restProps, htmlAttributes, { children: [(0, jsx_runtime_1.jsx)(ScrollButton, { direction: "left", isVisible: scrollState.isLeftVisible, onClick: () => scrollToNextItem('left'), onBackground: onBackground }), (0, jsx_runtime_1.jsx)(ScrollButton, { direction: "right", isVisible: scrollState.isRightVisible, onClick: () => scrollToNextItem('right'), onBackground: onBackground }), (0, jsx_runtime_1.jsx)(TabsContext.Provider, { value: {
fill,
firstTabId,
isValuePresent,
onChange,
registerTab,
scrollTabIntoView,
size,
unregisterTab,
value,
}, children: (0, jsx_runtime_1.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 = (0, react_2.useRef)(null);
// Create a merged ref that handles both ref objects and ref functions
const mergedRef = (0, react_1.useMergeRefs)([
internalRef,
ref,
]);
// Register/unregister tab for keyboard navigation
(0, react_2.useEffect)(() => {
registerTab(tabId, internalRef);
return () => {
unregisterTab(tabId);
};
}, [tabId, registerTab, unregisterTab]);
const baseClasses = (0, classnames_1.default)(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 = (0, classnames_1.default)('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 ((0, jsx_runtime_1.jsxs)(tooltip_1.Tooltip, Object.assign({ type: "simple" }, tooltipProps === null || tooltipProps === void 0 ? void 0 : tooltipProps.root, { isDisabled: description === undefined, children: [(0, jsx_runtime_1.jsx)(tooltip_1.Tooltip.Trigger, Object.assign({}, tooltipProps === null || tooltipProps === void 0 ? void 0 : tooltipProps.trigger, { hasButtonWrapper: true, children: (0, jsx_runtime_1.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' && (0, jsx_runtime_1.jsx)("span", { className: "ndl-tab-underline" })] })) })), (0, jsx_runtime_1.jsx)(tooltip_1.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 ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: value === tabId ? ((0, jsx_runtime_1.jsx)(Component, Object.assign({ role: "tabpanel", id: getTabPanelId(tabId), "aria-labelledby": tabId, style: style, className: (0, classnames_1.default)(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 = (0, classnames_1.default)('ndl-tab-badge', className);
return ((0, jsx_runtime_1.jsx)(typography_1.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,
});
exports.Tabs = Tabs;
//# sourceMappingURL=Tabs.js.map