@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
268 lines • 15.4 kB
JavaScript
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 { 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 React, { createContext, forwardRef, useContext, useEffect, useRef, useState, } from 'react';
import { ConditionalWrap } from '../conditional-wrap';
import { useIsInsideDialog } from '../dialog';
import { Divider } from '../divider';
import { IconButton } from '../icon-button';
import { ChevronRightIconOutline, XMarkIconOutline } 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 MenuComponent = forwardRef(function MenuComponent({ children, isOpen: controlledOpen, onClose, isRoot, anchorRef, as, className, placement, minWidth, title, isDisabled, description, icon, isPortaled = true, portalTarget, htmlAttributes, strategy, }, 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, icon: 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: isNested ? -1 : 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 MenuItem = forwardRef(function MenuItem({ title, className, style, icon, description, isDisabled, as, onClick, onFocus, htmlAttributes, id, }, forwardedRef) {
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 classes = classNames(`ndl-menu-item`, className, {
'ndl-disabled': isDisabled,
});
const ref = useMergeRefs([item.ref, forwardedRef]);
const Component = as !== null && as !== void 0 ? as : 'button';
return (_jsx(_Fragment, { children: _jsx(Component, Object.assign({ className: classes, ref: ref, type: "button", role: "menuitem", tabIndex: isActive ? 0 : -1, disabled: isDisabled }, htmlAttributes, 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);
},
style: style,
}), { children: _jsxs("div", { className: "ndl-menu-item-inner", children: [Boolean(icon) && _jsx("div", { className: "ndl-menu-item-icon", children: icon }), _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 }))] })] }) })) }));
});
const NestedMenuItem = forwardRef(function MenuItem({ title, isDisabled, className, description, icon, as, onFocus, onClick, htmlAttributes, }, forwardedRef) {
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 Component = as !== null && as !== void 0 ? as : 'button';
const ref = useMergeRefs([item.ref, forwardedRef]);
const classes = classNames(`ndl-menu-item`, className, {
'ndl-disabled': isDisabled,
});
return (_jsx(Component, Object.assign({ className: classes, ref: ref, type: "button", role: "menuitem", tabIndex: isActive ? 0 : -1, disabled: isDisabled }, htmlAttributes, 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);
},
}), { children: _jsxs("div", { className: "ndl-menu-item-inner", children: [Boolean(icon) && _jsx("div", { className: "ndl-menu-item-icon", children: icon }), _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 }))] }), _jsx("span", { className: "ndl-menu-item-chevron", children: _jsx(ChevronRightIconOutline, {}) })] }) })));
});
const MenuWrapper = forwardRef(function Menu(props, ref) {
const parentId = useFloatingParentNodeId();
if (parentId === null) {
return (_jsx(FloatingTree, { children: _jsx(MenuComponent, Object.assign({ ref: ref }, props, { isRoot: true })) }));
}
return _jsx(MenuComponent, Object.assign({ ref: ref }, props));
});
const MenuItems = React.forwardRef(function MenuItems({ 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 }, htmlAttributes, { children: children })));
});
const MenuDivider = forwardRef(function MenuDivider(props, ref) {
return _jsx(Divider, Object.assign({ ref: ref }, props));
});
const MenuSubheader = (props) => (_jsx("div", { className: "ndl-menu-subheader", children: _jsx("div", { className: "ndl-menu-subheader-title", children: props.title }) }));
const MenuHeader = forwardRef(function MenuHeader({ as, title, description, className, htmlAttributes, }, forwardedRef) {
const Component = as !== null && as !== void 0 ? as : 'div';
const menu = useContext(MenuContext);
const item = useListItem({ label: null });
const tree = useFloatingTree();
const ref = useMergeRefs([item.ref, forwardedRef]);
const classes = classNames('ndl-menu-header', className);
return (_jsxs(Component, { className: classes, children: [_jsxs("div", { className: "n-flex n-flex-col", children: [_jsx("div", { className: "ndl-menu-header-title", children: title }), Boolean(description) && (_jsx("div", { className: "ndl-menu-header-description", children: description }))] }), _jsx(IconButton, { className: "ndl-menu-header-close-button", ariaLabel: "Close", isClean: true, htmlAttributes: Object.assign(Object.assign(Object.assign({}, htmlAttributes), { tabIndex: 0 }), menu.getItemProps({
onClick(event) {
var _a;
(_a = htmlAttributes === null || htmlAttributes === void 0 ? void 0 : htmlAttributes.onClick) === null || _a === void 0 ? void 0 : _a.call(htmlAttributes, event);
tree === null || tree === void 0 ? void 0 : tree.events.emit('click');
},
onFocus(event) {
var _a;
(_a = htmlAttributes === null || htmlAttributes === void 0 ? void 0 : htmlAttributes.onFocus) === null || _a === void 0 ? void 0 : _a.call(htmlAttributes, event);
menu.setHasFocusInside(true);
},
})), ref: ref, children: _jsx(XMarkIconOutline, {}) })] }));
});
const Menu = Object.assign(MenuWrapper, {
Divider: MenuDivider,
Header: MenuHeader,
Item: MenuItem,
Items: MenuItems,
Subheader: MenuSubheader,
});
export { Menu };
//# sourceMappingURL=ContextMenu.js.map