@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
262 lines • 14.7 kB
JavaScript
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, flip, FloatingFocusManager, FloatingList, FloatingNode, FloatingPortal, FloatingTree, offset, safePolygon, shift, useClick, useDismiss, useFloating, useFloatingNodeId, useFloatingParentNodeId, useFloatingTree, useHover, useInteractions, useListItem, useListNavigation, useMergeRefs, useRole, useTypeahead, } from '@floating-ui/react';
import classNames from 'classnames';
import { createContext, useContext, useEffect, useRef, useState } from 'react';
import { ConditionalWrap } from '../conditional-wrap';
import { useIsInsideDialog } from '../dialog/dialog-context';
import { Divider } from '../divider';
import { ChevronRightIconOutline } from '../icons';
import { placementTranslation } from '../popover';
import { useNeedleTheme } from '../theme';
const MenuContext = createContext({
activeIndex: null,
getItemProps: () => ({}),
isOpen: false,
// eslint-disable-next-line @typescript-eslint/no-empty-function
setActiveIndex: () => { },
// eslint-disable-next-line @typescript-eslint/no-empty-function
setHasFocusInside: () => { },
});
const MenuWrapper = (props) => {
const parentId = useFloatingParentNodeId();
if (parentId === null) {
return (_jsx(FloatingTree, { children: _jsx(MenuComponent, Object.assign({}, props, { isRoot: true })) }));
}
return _jsx(MenuComponent, Object.assign({}, props));
};
const MenuComponent = ({ children, isOpen: controlledOpen, onClose, isRoot, anchorRef, as, className, placement, minWidth, title, isDisabled, description, icon, isPortaled = true, portalTarget, htmlAttributes, strategy, ref: forwardedRef, }) => {
const [isOpen, setIsOpen] = useState(false);
const [hasFocusInside, setHasFocusInside] = useState(false);
const [activeIndex, setActiveIndex] = useState(null);
const elementsRef = useRef([]);
const labelsRef = useRef([]);
const parent = useContext(MenuContext);
const isInsideDialog = useIsInsideDialog();
const tree = useFloatingTree();
const nodeId = useFloatingNodeId();
const parentId = useFloatingParentNodeId();
const item = useListItem();
const { themeClassName } = useNeedleTheme();
useEffect(() => {
if (controlledOpen === undefined) {
return;
}
setIsOpen(controlledOpen);
}, [controlledOpen]);
useEffect(() => {
if (isOpen) {
setActiveIndex(0);
}
}, [isOpen]);
const Component = as !== null && as !== void 0 ? as : 'div';
const isNested = parentId !== null;
const defaultPlacement = isNested ? 'right-start' : 'bottom-start';
const { floatingStyles, refs, context } = useFloating({
elements: {
reference: anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.current,
},
middleware: [
offset({
alignmentAxis: isNested ? -4 : 0,
mainAxis: isNested ? 0 : 4,
}),
flip({
fallbackPlacements: ['left-start', 'right-start'],
}),
shift(),
],
nodeId,
onOpenChange: (open, event) => {
if (controlledOpen === undefined) {
setIsOpen(open);
}
if (!open) {
if (event instanceof PointerEvent) {
onClose === null || onClose === void 0 ? void 0 : onClose(event, { type: 'backdropClick' });
}
else if (event instanceof KeyboardEvent) {
onClose === null || onClose === void 0 ? void 0 : onClose(event, { type: 'escapeKeyDown' });
}
}
},
open: isOpen,
placement: placement ? placementTranslation[placement] : defaultPlacement,
strategy: strategy !== null && strategy !== void 0 ? strategy : (isInsideDialog ? 'fixed' : 'absolute'),
whileElementsMounted: autoUpdate,
});
const hover = useHover(context, {
delay: { open: 75 },
enabled: isNested,
handleClose: safePolygon({ blockPointerEvents: true }),
});
const click = useClick(context, {
event: 'mousedown',
ignoreMouse: isNested,
toggle: !isNested,
});
const role = useRole(context, { role: 'menu' });
const dismiss = useDismiss(context, { bubbles: true });
const listNavigation = useListNavigation(context, {
activeIndex,
listRef: elementsRef,
nested: isNested,
onNavigate: setActiveIndex,
});
const typeahead = useTypeahead(context, {
activeIndex,
listRef: labelsRef,
onMatch: isOpen ? setActiveIndex : undefined,
});
const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions([hover, click, role, dismiss, listNavigation, typeahead]);
// Event emitter allows you to communicate across tree components.
// This effect closes all menus when an item gets clicked anywhere
// in the tree.
useEffect(() => {
if (!tree) {
return;
}
function handleTreeClick(data) {
if (controlledOpen === undefined) {
setIsOpen(false);
}
onClose === null || onClose === void 0 ? void 0 : onClose(undefined, { id: data === null || data === void 0 ? void 0 : data.id, type: 'itemClick' });
}
function onSubMenuOpen(event) {
if (event.nodeId !== nodeId && event.parentId === parentId) {
if (controlledOpen === undefined) {
setIsOpen(false);
}
onClose === null || onClose === void 0 ? void 0 : onClose(undefined, { type: 'itemClick' });
}
}
tree.events.on('click', handleTreeClick);
tree.events.on('menuopen', onSubMenuOpen);
return () => {
tree.events.off('click', handleTreeClick);
tree.events.off('menuopen', onSubMenuOpen);
};
}, [tree, nodeId, parentId, onClose, controlledOpen]);
useEffect(() => {
if (isOpen && tree) {
tree.events.emit('menuopen', { nodeId, parentId });
}
}, [tree, isOpen, nodeId, parentId]);
const menuClasses = classNames('ndl-menu', themeClassName, className);
const ref = useMergeRefs([refs.setReference, item.ref, forwardedRef]);
return (_jsxs(FloatingNode, { id: nodeId, children: [isRoot !== true && (_jsx(NestedMenuItem, { ref: ref, className: isNested ? 'MenuItem' : 'RootMenu', isDisabled: isDisabled, htmlAttributes: Object.assign(Object.assign({ 'data-focus-inside': hasFocusInside ? '' : undefined, 'data-nested': isNested ? '' : undefined, 'data-open': isOpen ? '' : undefined, role: isNested ? 'menuitem' : undefined, tabIndex: !isNested
? undefined
: parent.activeIndex === item.index
? 0
: -1 }, htmlAttributes), getReferenceProps(parent.getItemProps({
onFocus(event) {
var _a;
(_a = htmlAttributes === null || htmlAttributes === void 0 ? void 0 : htmlAttributes.onFocus) === null || _a === void 0 ? void 0 : _a.call(htmlAttributes, event);
setHasFocusInside(false);
parent.setHasFocusInside(true);
},
}))), title: title, description: description, leadingVisual: icon })), _jsx(MenuContext.Provider, { value: {
activeIndex,
getItemProps,
isOpen: isDisabled === true ? false : isOpen,
setActiveIndex,
setHasFocusInside,
}, children: _jsx(FloatingList, { elementsRef: elementsRef, labelsRef: labelsRef, children: isOpen && (_jsx(ConditionalWrap, { shouldWrap: isPortaled, wrap: (wrapChildren) => (_jsx(FloatingPortal, { root: portalTarget, children: wrapChildren })), children: _jsx(FloatingFocusManager, { context: context, modal: false, initialFocus: 0, returnFocus: !isNested, closeOnFocusOut: true, guards: true, children: _jsx(Component, Object.assign({ ref: refs.setFloating, className: menuClasses, style: Object.assign({ minWidth: minWidth !== undefined ? `${minWidth}px` : undefined }, floatingStyles) }, getFloatingProps(), { children: children })) }) })) }) })] }));
};
const MenuItemComponent = (_a) => {
var { title, leadingContent, trailingContent, description, isDisabled, as, className, style, htmlAttributes, ref } = _a, restProps = __rest(_a, ["title", "leadingContent", "trailingContent", "description", "isDisabled", "as", "className", "style", "htmlAttributes", "ref"]);
const classes = classNames(`ndl-menu-item`, className, {
'ndl-disabled': isDisabled,
});
const Component = as !== null && as !== void 0 ? as : 'button';
return (_jsx(Component, Object.assign({ className: classes, ref: ref, type: "button", role: "menuitem", disabled: isDisabled, style: style }, restProps, htmlAttributes, { children: _jsxs("div", { className: "ndl-menu-item-inner", children: [Boolean(leadingContent) && (_jsx("div", { className: "ndl-menu-item-leading-content", children: leadingContent })), _jsxs("div", { className: "ndl-menu-item-title-wrapper", children: [_jsx("div", { className: "ndl-menu-item-title", children: title }), Boolean(description) && (_jsx("div", { className: "ndl-menu-item-description", children: description }))] }), Boolean(trailingContent) && (_jsx("div", { className: "ndl-menu-item-trailing-content", children: trailingContent }))] }) })));
};
const MenuItem = ({ title, className, style, leadingVisual, trailingContent, description, isDisabled, as, onClick, onFocus, htmlAttributes, id, ref, }) => {
const menu = useContext(MenuContext);
const itemLabel = typeof title === 'string' ? title : undefined;
const item = useListItem({ label: isDisabled === true ? null : itemLabel });
const tree = useFloatingTree();
const isActive = item.index === menu.activeIndex;
const mergedRefs = useMergeRefs([item.ref, ref]);
return (_jsx(MenuItemComponent, { as: as !== null && as !== void 0 ? as : 'button', style: style, className: className, ref: mergedRefs, title: title, description: description, leadingContent: leadingVisual, trailingContent: trailingContent, isDisabled: isDisabled, htmlAttributes: Object.assign(Object.assign(Object.assign({}, htmlAttributes), { tabIndex: isActive ? 0 : -1 }), menu.getItemProps({
onClick(event) {
onClick === null || onClick === void 0 ? void 0 : onClick(event);
tree === null || tree === void 0 ? void 0 : tree.events.emit('click', { id });
},
onFocus(event) {
onFocus === null || onFocus === void 0 ? void 0 : onFocus(event);
menu.setHasFocusInside(true);
},
id: id,
style: style,
})) }));
};
const NestedMenuItem = ({ title, isDisabled, description, leadingVisual, as, onFocus, onClick, className, style, htmlAttributes, id, ref, }) => {
const menu = useContext(MenuContext);
const itemLabel = typeof title === 'string' ? title : undefined;
const item = useListItem({ label: isDisabled === true ? null : itemLabel });
const isActive = item.index === menu.activeIndex;
const mergedRefs = useMergeRefs([item.ref, ref]);
return (_jsx(MenuItemComponent, { as: as !== null && as !== void 0 ? as : 'button', style: style, className: className, ref: mergedRefs, title: title, description: description, leadingContent: leadingVisual, trailingContent: _jsx(ChevronRightIconOutline, { className: "ndl-menu-item-chevron" }), isDisabled: isDisabled, htmlAttributes: Object.assign(Object.assign(Object.assign(Object.assign({}, htmlAttributes), { tabIndex: isActive ? 0 : -1 }), menu.getItemProps({
onClick(event) {
onClick === null || onClick === void 0 ? void 0 : onClick(event);
},
onFocus(event) {
onFocus === null || onFocus === void 0 ? void 0 : onFocus(event);
menu.setHasFocusInside(true);
},
onTouchStart() {
menu.setHasFocusInside(true);
},
})), { id: id }) }));
};
const CategoryItem = (_a) => {
var { children, className, style, as, htmlAttributes, ref } = _a, restProps = __rest(_a, ["children", "className", "style", "as", "htmlAttributes", "ref"]);
const classes = classNames('ndl-menu-category-item', className);
const Component = as !== null && as !== void 0 ? as : 'div';
return (_jsx(Component, Object.assign({ className: classes, style: style, ref: ref }, restProps, htmlAttributes, { children: children })));
};
const MenuItems = (_a) => {
var { as, children, className, htmlAttributes, style, ref } = _a, restProps = __rest(_a, ["as", "children", "className", "htmlAttributes", "style", "ref"]);
const classes = classNames('ndl-menu-items', className);
const Component = as !== null && as !== void 0 ? as : 'div';
return (_jsx(Component, Object.assign({ className: classes, style: style, ref: ref }, restProps, htmlAttributes, { children: children })));
};
const Menu = Object.assign(MenuWrapper, {
CategoryItem: CategoryItem,
Divider: Divider,
Item: MenuItem,
Items: MenuItems,
});
export { Menu };
//# sourceMappingURL=Menu.js.map