1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { connect } from "react-redux";
6 import { RootState } from "store/store";
7 import { contextMenuActions, ContextMenuResource } from "store/context-menu/context-menu-actions";
8 import { ContextMenu as ContextMenuComponent, ContextMenuProps, ContextMenuItem } from "components/context-menu/context-menu";
9 import { createAnchorAt } from "components/popover/helpers";
10 import { ContextMenuActionSet, ContextMenuAction } from "./context-menu-action-set";
11 import { Dispatch } from "redux";
12 import { memoize } from "lodash";
13 import { sortMenuItems, ContextMenuKind, menuDirection } from "./menu-item-sort";
15 type DataProps = Pick<ContextMenuProps, "anchorEl" | "items" | "open"> & { resource?: ContextMenuResource };
17 const mapStateToProps = (state: RootState): DataProps => {
18 const { open, position, resource } = state.contextMenu;
19 const filteredItems = getMenuActionSet(resource).map(group =>
20 group.filter(item => {
21 if (resource && item.filters) {
22 // Execute all filters on this item, every returns true IFF all filters return true
23 return item.filters.every(filter => filter(state, resource));
31 anchorEl: resource ? createAnchorAt(position) : undefined,
38 type ActionProps = Pick<ContextMenuProps, "onClose"> & { onItemClick: (item: ContextMenuItem, resource?: ContextMenuResource) => void };
39 const mapDispatchToProps = (dispatch: Dispatch): ActionProps => ({
41 dispatch(contextMenuActions.CLOSE_CONTEXT_MENU());
43 onItemClick: (action: ContextMenuAction, resource?: ContextMenuResource) => {
44 dispatch(contextMenuActions.CLOSE_CONTEXT_MENU());
46 action.execute(dispatch, [resource]);
51 const handleItemClick = memoize(
52 (resource: DataProps["resource"], onItemClick: ActionProps["onItemClick"]): ContextMenuProps["onItemClick"] =>
54 onItemClick(item, { ...resource, fromContextMenu: true } as ContextMenuResource);
58 const mergeProps = ({ resource, ...dataProps }: DataProps, actionProps: ActionProps): ContextMenuProps => ({
61 onItemClick: handleItemClick(resource, actionProps.onItemClick),
64 export const ContextMenu = connect(mapStateToProps, mapDispatchToProps, mergeProps)(ContextMenuComponent);
66 const menuActionSets = new Map<string, ContextMenuActionSet>();
68 export const addMenuActionSet = (name: ContextMenuKind, itemSet: ContextMenuActionSet) => {
69 const sorted = itemSet.map(items => sortMenuItems(name, items, menuDirection.VERTICAL));
70 menuActionSets.set(name, sorted);
73 const emptyActionSet: ContextMenuActionSet = [];
74 const getMenuActionSet = (resource?: ContextMenuResource): ContextMenuActionSet =>
75 resource ? menuActionSets.get(resource.menuKind) || emptyActionSet : emptyActionSet;