UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

327 lines 19.8 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 } 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 { autoUpdate, Composite, CompositeItem, flip, FloatingFocusManager, FloatingList, FloatingPortal, offset, safePolygon, shift, useDismiss, useFloating, useFocus, useHover, useInteractions, useListItem, useListNavigation, useMergeRefs, useTransitionStyles, } from '@floating-ui/react'; import { tokens } from '@neo4j-ndl/base'; import classNames from 'classnames'; import { useEffect, useId, useRef, useState } from 'react'; import { IconIndicatorWrapper } from '../_common/IconIndicatorWrapper'; import { CleanIconButton } from '../clean-icon-button'; import { ConditionalWrap } from '../conditional-wrap'; import { Divider } from '../divider'; import { ChevronRightIconOutline, PinIcon } from '../icons'; import { Tooltip } from '../tooltip'; import { Typography } from '../typography'; import { SideNavCategoryContext, SideNavContext, useSideNavCategoryContext, useSideNavContext, } from './side-navigation-context'; /** * SideNav */ const SideNavComponent = (_a) => { var { children, className, style, htmlAttributes, isExpanded = false, shouldOverlayOnInteraction = true, ariaLabel, onPinButtonClick, expandedWidth, ref } = _a, restProps = __rest(_a, ["children", "className", "style", "htmlAttributes", "isExpanded", "shouldOverlayOnInteraction", "ariaLabel", "onPinButtonClick", "expandedWidth", "ref"]); const [isHovered, setIsHovered] = useState(false); const [hasFocusVisible, setHasFocusVisible] = useState(false); const rootRef = useRef(null); const isFloatingExpanded = shouldOverlayOnInteraction && (!isHovered ? hasFocusVisible : true); const classes = classNames('ndl-side-nav', 'ndl-side-nav-root', className, { 'ndl-side-nav-collapsed': isExpanded !== true && shouldOverlayOnInteraction !== true, 'ndl-side-nav-expanded': isExpanded, }); const innerClasses = classNames('ndl-side-nav-inner', { 'ndl-side-nav-hover': shouldOverlayOnInteraction === true && isFloatingExpanded === true && isExpanded !== true, }); const customStyle = Object.assign(Object.assign({}, style), (Boolean(expandedWidth) && { '--side-nav-width-expanded': typeof expandedWidth === 'string' ? expandedWidth : `${expandedWidth}px`, })); const mergedRef = useMergeRefs([ref, rootRef]); return (_jsx(SideNavContext.Provider, { value: { isExpanded, isHovered: isFloatingExpanded, // needs refactoring onPinButtonClick, shouldOverlayOnInteraction, }, children: _jsx("div", Object.assign({ className: classes, ref: mergedRef, style: customStyle, onMouseEnter: () => { setIsHovered(true); }, onMouseLeave: () => { setIsHovered(false); }, onFocusCapture: () => { // Delay slightly to let Composite's focus management settle requestAnimationFrame(() => { const activeElement = document.activeElement; // Check if focus is inside and visible (using :focus-visible on the active element) if (activeElement instanceof HTMLElement && rootRef.current !== null && rootRef.current.contains(activeElement) && activeElement.matches(':focus-visible')) { // Update state after another frame to let focus fully settle // This updates the context for consumers without disrupting focus requestAnimationFrame(() => { setHasFocusVisible(true); }); } }); }, onBlurCapture: () => { // Small delay to check if focus moved to another element inside requestAnimationFrame(() => { const activeElement = document.activeElement; const isInsideNav = activeElement instanceof HTMLElement && rootRef.current !== null && rootRef.current.contains(activeElement); // Check if focus is in a portaled floating menu const isInsideFloatingMenu = activeElement instanceof HTMLElement && activeElement.closest('.ndl-side-nav-popover') !== null; if ((isInsideNav || isInsideFloatingMenu) && activeElement instanceof HTMLElement && activeElement.matches(':focus-visible')) { // Focus stayed inside with focus-visible setHasFocusVisible(true); } else { // Focus left - collapse setHasFocusVisible(false); } }); } }, restProps, htmlAttributes, { children: _jsxs("div", Object.assign({ className: innerClasses, style: customStyle }, htmlAttributes, { children: [_jsx("nav", { className: "ndl-side-nav-nav", children: _jsx(Composite, { as: "ul", "aria-label": ariaLabel, role: "menubar", orientation: "vertical", "aria-orientation": "vertical", className: "ndl-side-nav-list", loop: true, children: children }) }), shouldOverlayOnInteraction === true && (_jsx("div", { className: "ndl-side-nav-footer", children: _jsx(PinButton, {}) }))] })) })) })); }; /** * SideNavListItem */ const SideNavListItem = (_a) => { var { children, className, style, htmlAttributes, ref } = _a, restProps = __rest(_a, ["children", "className", "style", "htmlAttributes", "ref"]); const classes = classNames('ndl-side-nav-list-item', className, {}); return (_jsxs("li", Object.assign({ role: "none", className: classes, style: style, ref: ref }, restProps, htmlAttributes, { children: [_jsx(SelectedIndicator, {}), children] }))); }; /** * NavItem */ const NavItem = (_a) => { var { icon, label, trailingElement, isActive, className, style, htmlAttributes, as, badge, ref } = _a, restProps = __rest(_a, ["icon", "label", "trailingElement", "isActive", "className", "style", "htmlAttributes", "as", "badge", "ref"]); const { isExpanded, isHovered, shouldOverlayOnInteraction } = useSideNavContext(); const categoryContext = useSideNavCategoryContext(); const isInCategory = categoryContext !== null; const item = useListItem(); const mergedRef = useMergeRefs([item.ref, ref]); const isActiveIndex = item.index === (categoryContext === null || categoryContext === void 0 ? void 0 : categoryContext.activeIndex); const Component = as !== null && as !== void 0 ? as : 'button'; const classes = classNames('ndl-side-nav-nav-item', className, { 'ndl-active': isActive === true, }); const Wrapper = isInCategory ? Component : CompositeItem; const componentProps = Object.assign(Object.assign(Object.assign({ className: classes, ref: mergedRef, role: 'menuitem', style: style }, (isInCategory && Object.assign(Object.assign({}, categoryContext === null || categoryContext === void 0 ? void 0 : categoryContext.getItemProps()), { tabIndex: isActiveIndex ? 0 : -1 }))), restProps), htmlAttributes); const wrapperProps = isInCategory ? componentProps : { render: _jsx(Component, Object.assign({}, componentProps)), }; return (_jsx(ConditionalWrap, { shouldWrap: isExpanded === false && !shouldOverlayOnInteraction && !isInCategory && Boolean(label), wrap: (children) => (_jsxs(Tooltip, { type: "simple", placement: "right", hoverDelay: { close: 0, open: shouldOverlayOnInteraction ? 100 : 0 }, children: [_jsx(Tooltip.Trigger, { hasButtonWrapper: true, children: children }), _jsx(Tooltip.Content, { children: label })] })), children: _jsx(Wrapper, Object.assign({}, wrapperProps, { children: _jsxs("div", { className: "ndl-side-nav-item-inner", children: [Boolean(icon) && (_jsx("div", { className: "ndl-side-nav-item-leading-element", children: _jsx(ConditionalWrap, { shouldWrap: Boolean(badge) && !isHovered && !isExpanded, wrap: (children) => { var _a; return (_jsx(IconIndicatorWrapper, { type: (_a = badge === null || badge === void 0 ? void 0 : badge.type) !== null && _a !== void 0 ? _a : 'info', children: children })); }, children: icon }) })), Boolean(label) && (_jsx(Typography, { variant: "body-medium", as: "div", className: "ndl-side-nav-item-label", children: label })), (Boolean(trailingElement) || Boolean(badge)) && (_jsxs("div", { className: "ndl-side-nav-item-trailing-element", children: [trailingElement, badge !== undefined && (_jsx(ItemBadge, { type: badge.type, number: badge.number }))] }))] }) })) })); }; /** * CategoryItem */ const CategoryItem = (_a) => { var _b; var { children, icon, label, isActive, className, style, htmlAttributes, badge, isMenuOpen = false, ref } = _a, restProps = __rest(_a, ["children", "icon", "label", "isActive", "className", "style", "htmlAttributes", "badge", "isMenuOpen", "ref"]); const floatingId = useId(); const { isExpanded, isHovered, shouldOverlayOnInteraction } = useSideNavContext(); const anchorRef = useRef(null); const [isOpen, setIsOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(null); const [isTooltipOpen, setIsTooltipOpen] = useState(false); const elementsRef = useRef([]); const classes = classNames('ndl-side-nav-category-item', className, { 'ndl-active': isActive === true, }); // Floating UI setup const { refs, context } = useFloating({ elements: { reference: anchorRef.current, }, middleware: [ offset(5), flip({ crossAxis: true, fallbackAxisSideDirection: 'end', padding: 5 }), shift({ padding: 5 }), ], onOpenChange: setIsOpen, open: isOpen || isMenuOpen, placement: 'right-start', strategy: 'fixed', whileElementsMounted: autoUpdate, }); const dismiss = useDismiss(context, { referencePress: false, }); const hover = useHover(context, { delay: { close: 130, open: 130 }, handleClose: safePolygon({ blockPointerEvents: false, requireIntent: false, }), }); const focus = useFocus(context); const listNavigation = useListNavigation(context, { activeIndex: activeIndex, focusItemOnHover: false, focusItemOnOpen: false, listRef: elementsRef, loop: true, nested: true, onNavigate: setActiveIndex, openOnArrowKeyDown: false, }); // Separate interactions: reference (no listNavigation), floating (with listNavigation) const refInteractions = useInteractions([dismiss, hover, focus]); const floatInteractions = useInteractions([dismiss, hover, listNavigation]); const { styles: transitionStyles } = useTransitionStyles(context, { duration: (_b = Number.parseInt(tokens.motion.duration.quick)) !== null && _b !== void 0 ? _b : 0, }); // Reset activeIndex when menu closes useEffect(() => { if (!context.open) { setActiveIndex(null); } }, [context.open]); const mergedRef = useMergeRefs([refs.setReference, ref]); return (_jsx(SideNavCategoryContext.Provider, { value: { activeIndex, getItemProps: floatInteractions.getItemProps, }, children: _jsx(ConditionalWrap, { shouldWrap: isExpanded === false && !shouldOverlayOnInteraction && Boolean(label), wrap: (children) => (_jsxs(Tooltip, { type: "simple", placement: "top", hoverDelay: { close: 0, open: shouldOverlayOnInteraction ? 100 : 0, }, isOpen: isTooltipOpen, onOpenChange: setIsTooltipOpen, children: [_jsx(Tooltip.Trigger, { hasButtonWrapper: true, children: children }), _jsx(Tooltip.Content, { className: "ndl-side-nav ndl-side-nav-category-menu-tooltip-content", children: label })] })), children: _jsxs(CompositeItem, { render: _jsx("button", Object.assign({}, refInteractions.getReferenceProps(Object.assign(Object.assign({ className: classes, ref: mergedRef, style }, restProps), htmlAttributes)), { // {...restProps} // {...htmlAttributes} role: "menuitem", "aria-haspopup": "menu", "aria-expanded": context.open, "aria-controls": floatingId, onFocus: (e) => { // Only show tooltip on focus-visible (keyboard navigation) if (e.target instanceof HTMLElement && e.target.matches(':focus-visible')) { setIsTooltipOpen(true); } // Call original handler if exists const originalOnFocus = refInteractions.getReferenceProps({}) .onFocus; originalOnFocus === null || originalOnFocus === void 0 ? void 0 : originalOnFocus(e); }, onBlur: (e) => { setIsTooltipOpen(false); // Call original handler if exists const originalOnBlur = refInteractions.getReferenceProps({}) .onBlur; originalOnBlur === null || originalOnBlur === void 0 ? void 0 : originalOnBlur(e); }, onKeyDown: (e) => { if (e.key === 'ArrowRight') { // open and move focus into submenu setIsOpen(true); setActiveIndex(0); // Defer focusing first item (if needed) to next tick requestAnimationFrame(() => { const el = elementsRef.current[0]; el === null || el === void 0 ? void 0 : el.focus(); }); e.preventDefault(); } // ArrowDown/ArrowUp: let Composite handle top-level roving focus. } })), children: [_jsxs("div", { className: "ndl-side-nav-item-inner", children: [Boolean(icon) && (_jsx("div", { className: "ndl-side-nav-item-leading-element", children: _jsx(ConditionalWrap, { shouldWrap: Boolean(badge) && !isHovered && !isExpanded, wrap: (children) => { var _a; return (_jsx(IconIndicatorWrapper, { type: (_a = badge === null || badge === void 0 ? void 0 : badge.type) !== null && _a !== void 0 ? _a : 'info', children: children })); }, children: icon }) })), Boolean(label) && (_jsx(Typography, { variant: "body-medium", as: "div", className: "ndl-side-nav-item-label", children: label })), _jsxs("div", { className: "ndl-side-nav-item-trailing-element", children: [badge && _jsx(ItemBadge, { type: badge.type, number: badge.number }), _jsx(ChevronRightIconOutline, { className: "n-size-4 n-text-neutral-icon" })] })] }), context.open && (_jsx(FloatingList, { elementsRef: elementsRef, children: _jsx(FloatingPortal, { children: _jsx(FloatingFocusManager, { context: context, modal: false, initialFocus: -1, returnFocus: true, closeOnFocusOut: true, guards: true, children: _jsx("ul", Object.assign({ id: floatingId, ref: refs.setFloating, className: "ndl-side-nav ndl-side-nav-popover ndl-side-nav-popover-list", style: Object.assign(Object.assign({}, context.floatingStyles), transitionStyles) }, floatInteractions.getFloatingProps(), { role: "menu", children: children })) }) }) }))] }) }) })); }; /** * CategoryHeader */ const CategoryHeader = (_a) => { var { children, className, ref, style, htmlAttributes } = _a, restProps = __rest(_a, ["children", "className", "ref", "style", "htmlAttributes"]); const { isExpanded, isHovered } = useSideNavContext(); const classes = classNames('ndl-side-nav-category-header', className, { 'ndl-side-nav-category-header-expanded': isExpanded || isHovered, }); return (_jsx(Typography, Object.assign({ ref: ref, variant: "label", as: "li", className: classes, htmlAttributes: Object.assign(Object.assign({}, htmlAttributes), { role: 'separator' }), style: style }, restProps, { children: isExpanded || isHovered ? children : _jsx(Divider, {}) }))); }; /** * SelectedIndicator */ const SelectedIndicator = () => { return _jsx("div", { className: "ndl-side-nav-selected-indicator" }); }; /** * SideNavDivider */ const SideNavDivider = () => { return (_jsx(Divider, { orientation: "horizontal", className: "ndl-side-nav-divider", as: "li" })); }; /** * ItemBadge */ const ItemBadge = (_a) => { var { number, type, ref, htmlAttributes, style, className } = _a, restProps = __rest(_a, ["number", "type", "ref", "htmlAttributes", "style", "className"]); useSideNavContext(); const badgeClasses = classNames('ndl-side-nav-item-badge', className, { 'ndl-danger': type === 'danger', 'ndl-info': type === 'info', 'ndl-warning': type === 'warning', }); return (_jsx(Typography, Object.assign({ as: "span", className: badgeClasses, variant: "subheading-small", htmlAttributes: Object.assign({ 'aria-label': `${number} notifications of type ${type}` }, htmlAttributes), style: style, ref: ref }, restProps, { children: number }))); }; /** * PinButton */ const PinButton = () => { const { isExpanded, shouldOverlayOnInteraction, onPinButtonClick } = useSideNavContext(); const classes = classNames('ndl-side-nav-pin-button'); if (!shouldOverlayOnInteraction) { return null; } return (_jsx(CleanIconButton, { onClick: onPinButtonClick, className: classes, description: "Pin", size: "medium", isActive: isExpanded, tooltipProps: { root: { autoUpdateOptions: { animationFrame: true, }, placement: 'right', }, }, children: _jsx(PinIcon, {}) })); }; const SideNavigation = Object.assign(SideNavComponent, { CategoryHeader: CategoryHeader, CategoryItem: CategoryItem, Divider: SideNavDivider, ItemBadge: ItemBadge, ListItem: SideNavListItem, NavItem, }); export { SideNavigation }; //# sourceMappingURL=SideNavigation.js.map