@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
362 lines • 23.4 kB
JavaScript
"use strict";
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.SideNavigation = 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 base_1 = require("@neo4j-ndl/base");
const classnames_1 = __importDefault(require("classnames"));
const react_2 = require("react");
const IconIndicatorWrapper_1 = require("../_common/IconIndicatorWrapper");
const clean_icon_button_1 = require("../clean-icon-button");
const conditional_wrap_1 = require("../conditional-wrap");
const divider_1 = require("../divider");
const Pin_1 = __importDefault(require("../icons/generated/custom/Pin"));
const ChevronRightIconOutline_1 = require("../icons/generated/heroIcons/ChevronRightIconOutline");
const tooltip_1 = require("../tooltip");
const typography_1 = require("../typography");
const side_navigation_context_1 = require("./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] = (0, react_2.useState)(false);
const [hasFocusVisible, setHasFocusVisible] = (0, react_2.useState)(false);
const [isCollapseTransitioning, setIsCollapseTransitioning] = (0, react_2.useState)(false);
const collapseTransitionTimeoutRef = (0, react_2.useRef)(null);
const rootRef = (0, react_2.useRef)(null);
const isFloatingExpanded = shouldOverlayOnInteraction && (!isHovered ? hasFocusVisible : true);
const classes = (0, classnames_1.default)('ndl-side-nav', 'ndl-side-nav-root', className, {
'ndl-side-nav-collapsed': isExpanded !== true && shouldOverlayOnInteraction !== true,
'ndl-side-nav-expanded': isExpanded,
});
const innerClasses = (0, classnames_1.default)('ndl-side-nav-inner', {
'ndl-side-nav-collapsing': isCollapseTransitioning,
'ndl-side-nav-hover': 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 = (0, react_1.useMergeRefs)([ref, rootRef]);
const collapseTransitionDuration = Number.parseInt(base_1.tokens.motion.duration.quick, 10);
(0, react_2.useEffect)(() => {
return () => {
if (collapseTransitionTimeoutRef.current !== null) {
clearTimeout(collapseTransitionTimeoutRef.current);
collapseTransitionTimeoutRef.current = null;
}
};
}, []);
return ((0, jsx_runtime_1.jsx)(side_navigation_context_1.SideNavContext.Provider, { value: {
isExpanded,
isHovered: isFloatingExpanded, // needs refactoring
onPinButtonClick,
shouldOverlayOnInteraction,
}, children: (0, jsx_runtime_1.jsx)("div", Object.assign({ className: classes, ref: mergedRef, style: customStyle, onMouseEnter: () => {
if (collapseTransitionTimeoutRef.current !== null) {
clearTimeout(collapseTransitionTimeoutRef.current);
collapseTransitionTimeoutRef.current = null;
}
setIsCollapseTransitioning(false);
setIsHovered(true);
}, onMouseLeave: () => {
const shouldDelayZIndexRemoval = shouldOverlayOnInteraction &&
!isExpanded &&
(isHovered || hasFocusVisible);
setIsHovered(false);
if (shouldDelayZIndexRemoval) {
if (collapseTransitionTimeoutRef.current !== null) {
clearTimeout(collapseTransitionTimeoutRef.current);
}
setIsCollapseTransitioning(true);
collapseTransitionTimeoutRef.current = setTimeout(() => {
collapseTransitionTimeoutRef.current = null;
setIsCollapseTransitioning(false);
}, collapseTransitionDuration);
}
}, 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: (0, jsx_runtime_1.jsxs)("div", { className: innerClasses, children: [(0, jsx_runtime_1.jsx)("nav", { className: "ndl-side-nav-nav", "aria-label": ariaLabel, children: (0, jsx_runtime_1.jsx)(react_1.Composite, { as: "ul", "aria-label": ariaLabel, role: "menubar", orientation: "vertical", "aria-orientation": "vertical", className: "ndl-side-nav-list", loop: true, children: children }) }), shouldOverlayOnInteraction === true && ((0, jsx_runtime_1.jsx)("div", { className: "ndl-side-nav-footer", children: (0, jsx_runtime_1.jsx)(PinButton, {}) }))] }) })) }));
};
/**
* SideNavListItem
*/
const SideNavListItem = (_a) => {
var { children, className, style, htmlAttributes, ref } = _a, restProps = __rest(_a, ["children", "className", "style", "htmlAttributes", "ref"]);
const classes = (0, classnames_1.default)('ndl-side-nav-list-item', className, {});
return ((0, jsx_runtime_1.jsxs)("li", Object.assign({ role: "none", className: classes, style: style, ref: ref }, restProps, htmlAttributes, { children: [(0, jsx_runtime_1.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 } = (0, side_navigation_context_1.useSideNavContext)();
const categoryContext = (0, side_navigation_context_1.useSideNavCategoryContext)();
const isInCategory = categoryContext !== null;
const item = (0, react_1.useListItem)();
const mergedRef = (0, react_1.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 = (0, classnames_1.default)('ndl-side-nav-nav-item', className, {
'ndl-active': isActive === true,
});
const Wrapper = isInCategory ? Component : react_1.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: (0, jsx_runtime_1.jsx)(Component, Object.assign({}, componentProps)),
};
return ((0, jsx_runtime_1.jsx)(conditional_wrap_1.ConditionalWrap, { shouldWrap: isExpanded === false &&
!shouldOverlayOnInteraction &&
!isInCategory &&
Boolean(label), wrap: (children) => ((0, jsx_runtime_1.jsxs)(tooltip_1.Tooltip, { type: "simple", placement: "right", hoverDelay: { close: 0, open: shouldOverlayOnInteraction ? 100 : 0 }, children: [(0, jsx_runtime_1.jsx)(tooltip_1.Tooltip.Trigger, { hasButtonWrapper: true, children: children }), (0, jsx_runtime_1.jsx)(tooltip_1.Tooltip.Content, { children: label })] })), children: (0, jsx_runtime_1.jsx)(Wrapper, Object.assign({}, wrapperProps, { children: (0, jsx_runtime_1.jsxs)("div", { className: "ndl-side-nav-item-inner", children: [Boolean(icon) && ((0, jsx_runtime_1.jsx)("div", { className: "ndl-side-nav-item-leading-element", children: (0, jsx_runtime_1.jsx)(conditional_wrap_1.ConditionalWrap, { shouldWrap: Boolean(badge) && !isHovered && !isExpanded, wrap: (children) => {
var _a;
return ((0, jsx_runtime_1.jsx)(IconIndicatorWrapper_1.IconIndicatorWrapper, { type: (_a = badge === null || badge === void 0 ? void 0 : badge.type) !== null && _a !== void 0 ? _a : 'info', children: children }));
}, children: icon }) })), Boolean(label) && ((0, jsx_runtime_1.jsx)(typography_1.Typography, { variant: "body-medium", as: "div", className: "ndl-side-nav-item-label", children: label })), (Boolean(trailingElement) || Boolean(badge)) && ((0, jsx_runtime_1.jsxs)("div", { className: "ndl-side-nav-item-trailing-element", children: [trailingElement, badge !== undefined && ((0, jsx_runtime_1.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 = (0, react_2.useId)();
const { isExpanded, isHovered, shouldOverlayOnInteraction } = (0, side_navigation_context_1.useSideNavContext)();
const anchorRef = (0, react_2.useRef)(null);
const [isOpen, setIsOpen] = (0, react_2.useState)(false);
const [activeIndex, setActiveIndex] = (0, react_2.useState)(null);
const [isTooltipOpen, setIsTooltipOpen] = (0, react_2.useState)(false);
const elementsRef = (0, react_2.useRef)([]);
const classes = (0, classnames_1.default)('ndl-side-nav-category-item', className, {
'ndl-active': isActive === true,
});
// Floating UI setup
const { refs, context } = (0, react_1.useFloating)({
elements: {
reference: anchorRef.current,
},
middleware: [
(0, react_1.offset)(5),
(0, react_1.flip)({ crossAxis: true, fallbackAxisSideDirection: 'end', padding: 5 }),
(0, react_1.shift)({ padding: 5 }),
],
onOpenChange: setIsOpen,
open: isOpen || isMenuOpen,
placement: 'right-start',
strategy: 'fixed',
whileElementsMounted: react_1.autoUpdate,
});
const dismiss = (0, react_1.useDismiss)(context, {
referencePress: false,
});
const hover = (0, react_1.useHover)(context, {
delay: { close: 130, open: 130 },
handleClose: (0, react_1.safePolygon)({
blockPointerEvents: false,
requireIntent: false,
}),
});
const focus = (0, react_1.useFocus)(context);
const listNavigation = (0, react_1.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 = (0, react_1.useInteractions)([dismiss, hover, focus]);
const floatInteractions = (0, react_1.useInteractions)([dismiss, hover, listNavigation]);
const { styles: transitionStyles } = (0, react_1.useTransitionStyles)(context, {
duration: (_b = Number.parseInt(base_1.tokens.motion.duration.quick)) !== null && _b !== void 0 ? _b : 0,
});
// Reset activeIndex when menu closes
(0, react_2.useEffect)(() => {
if (!context.open) {
setActiveIndex(null);
}
}, [context.open]);
const mergedRef = (0, react_1.useMergeRefs)([refs.setReference, ref]);
return ((0, jsx_runtime_1.jsx)(side_navigation_context_1.SideNavCategoryContext.Provider, { value: {
activeIndex,
getItemProps: floatInteractions.getItemProps,
}, children: (0, jsx_runtime_1.jsx)(conditional_wrap_1.ConditionalWrap, { shouldWrap: isExpanded === false && !shouldOverlayOnInteraction && Boolean(label), wrap: (children) => ((0, jsx_runtime_1.jsxs)(tooltip_1.Tooltip, { type: "simple", placement: "top", hoverDelay: {
close: 0,
open: shouldOverlayOnInteraction ? 100 : 0,
}, isOpen: isTooltipOpen, onOpenChange: setIsTooltipOpen, children: [(0, jsx_runtime_1.jsx)(tooltip_1.Tooltip.Trigger, { hasButtonWrapper: true, children: children }), (0, jsx_runtime_1.jsx)(tooltip_1.Tooltip.Content, { className: "ndl-side-nav ndl-side-nav-category-menu-tooltip-content", children: label })] })), children: (0, jsx_runtime_1.jsxs)(react_1.CompositeItem, { render: (0, jsx_runtime_1.jsx)("button", Object.assign({ type: "button" }, 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: [(0, jsx_runtime_1.jsxs)("div", { className: "ndl-side-nav-item-inner", children: [Boolean(icon) && ((0, jsx_runtime_1.jsx)("div", { className: "ndl-side-nav-item-leading-element", children: (0, jsx_runtime_1.jsx)(conditional_wrap_1.ConditionalWrap, { shouldWrap: Boolean(badge) && !isHovered && !isExpanded, wrap: (children) => {
var _a;
return ((0, jsx_runtime_1.jsx)(IconIndicatorWrapper_1.IconIndicatorWrapper, { type: (_a = badge === null || badge === void 0 ? void 0 : badge.type) !== null && _a !== void 0 ? _a : 'info', children: children }));
}, children: icon }) })), Boolean(label) && ((0, jsx_runtime_1.jsx)(typography_1.Typography, { variant: "body-medium", as: "div", className: "ndl-side-nav-item-label", children: label })), (0, jsx_runtime_1.jsxs)("div", { className: "ndl-side-nav-item-trailing-element", children: [badge && (0, jsx_runtime_1.jsx)(ItemBadge, { type: badge.type, number: badge.number }), (0, jsx_runtime_1.jsx)(ChevronRightIconOutline_1.ChevronRightIconOutline, { className: "n-size-4 n-text-neutral-icon" })] })] }), context.open && ((0, jsx_runtime_1.jsx)(react_1.FloatingList, { elementsRef: elementsRef, children: (0, jsx_runtime_1.jsx)(react_1.FloatingPortal, { children: (0, jsx_runtime_1.jsx)(react_1.FloatingFocusManager, { context: context, modal: false, initialFocus: -1, returnFocus: true, closeOnFocusOut: true, guards: true, children: (0, jsx_runtime_1.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 } = (0, side_navigation_context_1.useSideNavContext)();
const classes = (0, classnames_1.default)('ndl-side-nav-category-header', className, {
'ndl-side-nav-category-header-expanded': isExpanded || isHovered,
});
return ((0, jsx_runtime_1.jsx)(typography_1.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 : (0, jsx_runtime_1.jsx)(divider_1.Divider, {}) })));
};
/**
* SelectedIndicator
*/
const SelectedIndicator = () => {
return (0, jsx_runtime_1.jsx)("div", { className: "ndl-side-nav-selected-indicator" });
};
/**
* SideNavDivider
*/
const SideNavDivider = () => {
return ((0, jsx_runtime_1.jsx)(divider_1.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"]);
(0, side_navigation_context_1.useSideNavContext)();
const badgeClasses = (0, classnames_1.default)('ndl-side-nav-item-badge', className, {
'ndl-danger': type === 'danger',
'ndl-info': type === 'info',
'ndl-warning': type === 'warning',
});
return ((0, jsx_runtime_1.jsx)(typography_1.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 } = (0, side_navigation_context_1.useSideNavContext)();
const classes = (0, classnames_1.default)('ndl-side-nav-pin-button');
if (!shouldOverlayOnInteraction) {
return null;
}
return ((0, jsx_runtime_1.jsx)(clean_icon_button_1.CleanIconButton, { onClick: onPinButtonClick, className: classes, description: "Pin", size: "medium", isActive: isExpanded, tooltipProps: {
root: {
autoUpdateOptions: {
animationFrame: true,
},
placement: 'right',
},
}, children: (0, jsx_runtime_1.jsx)(Pin_1.default, {}) }));
};
const SideNavigation = Object.assign(SideNavComponent, {
CategoryHeader: CategoryHeader,
CategoryItem: CategoryItem,
Divider: SideNavDivider,
ItemBadge: ItemBadge,
ListItem: SideNavListItem,
NavItem,
});
exports.SideNavigation = SideNavigation;
//# sourceMappingURL=SideNavigation.js.map