@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
268 lines • 15.7 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.Menu = 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 = require("react");
const conditional_wrap_1 = require("../conditional-wrap");
const dialog_context_1 = require("../dialog/dialog-context");
const divider_1 = require("../divider");
const icons_1 = require("../icons");
const popover_1 = require("../popover");
const theme_1 = require("../theme");
const MenuContext = (0, react_2.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 = (0, react_1.useFloatingParentNodeId)();
if (parentId === null) {
return ((0, jsx_runtime_1.jsx)(react_1.FloatingTree, { children: (0, jsx_runtime_1.jsx)(MenuComponent, Object.assign({}, props, { isRoot: true })) }));
}
return (0, jsx_runtime_1.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] = (0, react_2.useState)(false);
const [hasFocusInside, setHasFocusInside] = (0, react_2.useState)(false);
const [activeIndex, setActiveIndex] = (0, react_2.useState)(null);
const elementsRef = (0, react_2.useRef)([]);
const labelsRef = (0, react_2.useRef)([]);
const parent = (0, react_2.useContext)(MenuContext);
const isInsideDialog = (0, dialog_context_1.useIsInsideDialog)();
const tree = (0, react_1.useFloatingTree)();
const nodeId = (0, react_1.useFloatingNodeId)();
const parentId = (0, react_1.useFloatingParentNodeId)();
const item = (0, react_1.useListItem)();
const { themeClassName } = (0, theme_1.useNeedleTheme)();
(0, react_2.useEffect)(() => {
if (controlledOpen === undefined) {
return;
}
setIsOpen(controlledOpen);
}, [controlledOpen]);
(0, react_2.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 } = (0, react_1.useFloating)({
elements: {
reference: anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.current,
},
middleware: [
(0, react_1.offset)({
alignmentAxis: isNested ? -4 : 0,
mainAxis: isNested ? 0 : 4,
}),
(0, react_1.flip)({
fallbackPlacements: ['left-start', 'right-start'],
}),
(0, react_1.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 ? popover_1.placementTranslation[placement] : defaultPlacement,
strategy: strategy !== null && strategy !== void 0 ? strategy : (isInsideDialog ? 'fixed' : 'absolute'),
whileElementsMounted: react_1.autoUpdate,
});
const hover = (0, react_1.useHover)(context, {
delay: { open: 75 },
enabled: isNested,
handleClose: (0, react_1.safePolygon)({ blockPointerEvents: true }),
});
const click = (0, react_1.useClick)(context, {
event: 'mousedown',
ignoreMouse: isNested,
toggle: !isNested,
});
const role = (0, react_1.useRole)(context, { role: 'menu' });
const dismiss = (0, react_1.useDismiss)(context, { bubbles: true });
const listNavigation = (0, react_1.useListNavigation)(context, {
activeIndex,
listRef: elementsRef,
nested: isNested,
onNavigate: setActiveIndex,
});
const typeahead = (0, react_1.useTypeahead)(context, {
activeIndex,
listRef: labelsRef,
onMatch: isOpen ? setActiveIndex : undefined,
});
const { getReferenceProps, getFloatingProps, getItemProps } = (0, react_1.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.
(0, react_2.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]);
(0, react_2.useEffect)(() => {
if (isOpen && tree) {
tree.events.emit('menuopen', { nodeId, parentId });
}
}, [tree, isOpen, nodeId, parentId]);
const menuClasses = (0, classnames_1.default)('ndl-menu', themeClassName, className);
const ref = (0, react_1.useMergeRefs)([refs.setReference, item.ref, forwardedRef]);
return ((0, jsx_runtime_1.jsxs)(react_1.FloatingNode, { id: nodeId, children: [isRoot !== true && ((0, jsx_runtime_1.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 })), (0, jsx_runtime_1.jsx)(MenuContext.Provider, { value: {
activeIndex,
getItemProps,
isOpen: isDisabled === true ? false : isOpen,
setActiveIndex,
setHasFocusInside,
}, children: (0, jsx_runtime_1.jsx)(react_1.FloatingList, { elementsRef: elementsRef, labelsRef: labelsRef, children: isOpen && ((0, jsx_runtime_1.jsx)(conditional_wrap_1.ConditionalWrap, { shouldWrap: isPortaled, wrap: (wrapChildren) => ((0, jsx_runtime_1.jsx)(react_1.FloatingPortal, { root: portalTarget, children: wrapChildren })), children: (0, jsx_runtime_1.jsx)(react_1.FloatingFocusManager, { context: context, modal: false, initialFocus: 0, returnFocus: !isNested, closeOnFocusOut: true, guards: true, children: (0, jsx_runtime_1.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 = (0, classnames_1.default)(`ndl-menu-item`, className, {
'ndl-disabled': isDisabled,
});
const Component = as !== null && as !== void 0 ? as : 'button';
return ((0, jsx_runtime_1.jsx)(Component, Object.assign({ className: classes, ref: ref, type: "button", role: "menuitem", disabled: isDisabled, style: style }, restProps, htmlAttributes, { children: (0, jsx_runtime_1.jsxs)("div", { className: "ndl-menu-item-inner", children: [Boolean(leadingContent) && ((0, jsx_runtime_1.jsx)("div", { className: "ndl-menu-item-leading-content", children: leadingContent })), (0, jsx_runtime_1.jsxs)("div", { className: "ndl-menu-item-title-wrapper", children: [(0, jsx_runtime_1.jsx)("div", { className: "ndl-menu-item-title", children: title }), Boolean(description) && ((0, jsx_runtime_1.jsx)("div", { className: "ndl-menu-item-description", children: description }))] }), Boolean(trailingContent) && ((0, jsx_runtime_1.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 = (0, react_2.useContext)(MenuContext);
const itemLabel = typeof title === 'string' ? title : undefined;
const item = (0, react_1.useListItem)({ label: isDisabled === true ? null : itemLabel });
const tree = (0, react_1.useFloatingTree)();
const isActive = item.index === menu.activeIndex;
const mergedRefs = (0, react_1.useMergeRefs)([item.ref, ref]);
return ((0, jsx_runtime_1.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 = (0, react_2.useContext)(MenuContext);
const itemLabel = typeof title === 'string' ? title : undefined;
const item = (0, react_1.useListItem)({ label: isDisabled === true ? null : itemLabel });
const isActive = item.index === menu.activeIndex;
const mergedRefs = (0, react_1.useMergeRefs)([item.ref, ref]);
return ((0, jsx_runtime_1.jsx)(MenuItemComponent, { as: as !== null && as !== void 0 ? as : 'button', style: style, className: className, ref: mergedRefs, title: title, description: description, leadingContent: leadingVisual, trailingContent: (0, jsx_runtime_1.jsx)(icons_1.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 = (0, classnames_1.default)('ndl-menu-category-item', className);
const Component = as !== null && as !== void 0 ? as : 'div';
return ((0, jsx_runtime_1.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 = (0, classnames_1.default)('ndl-menu-items', className);
const Component = as !== null && as !== void 0 ? as : 'div';
return ((0, jsx_runtime_1.jsx)(Component, Object.assign({ className: classes, style: style, ref: ref }, restProps, htmlAttributes, { children: children })));
};
const Menu = Object.assign(MenuWrapper, {
CategoryItem: CategoryItem,
Divider: divider_1.Divider,
Item: MenuItem,
Items: MenuItems,
});
exports.Menu = Menu;
//# sourceMappingURL=Menu.js.map