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 { sortByProperty } from "common/array-utils";
14 import { sortMenuItems, ContextMenuKind } from "./menu-item-sort";
16 type DataProps = Pick<ContextMenuProps, "anchorEl" | "items" | "open"> & { resource?: ContextMenuResource };
18 const mapStateToProps = (state: RootState): DataProps => {
19 const { open, position, resource } = state.contextMenu;
20 const filteredItems = getMenuActionSet(resource).map(group =>
21 group.filter(item => {
22 if (resource && item.filters) {
23 // Execute all filters on this item, every returns true IFF all filters return true
24 return item.filters.every(filter => filter(state, resource));
32 anchorEl: resource ? createAnchorAt(position) : undefined,
39 type ActionProps = Pick<ContextMenuProps, "onClose"> & { onItemClick: (item: ContextMenuItem, resource?: ContextMenuResource) => void };
40 const mapDispatchToProps = (dispatch: Dispatch): ActionProps => ({
42 dispatch(contextMenuActions.CLOSE_CONTEXT_MENU());
44 onItemClick: (action: ContextMenuAction, resource?: ContextMenuResource) => {
45 dispatch(contextMenuActions.CLOSE_CONTEXT_MENU());
47 action.execute(dispatch, [resource]);
52 const handleItemClick = memoize(
53 (resource: DataProps["resource"], onItemClick: ActionProps["onItemClick"]): ContextMenuProps["onItemClick"] =>
55 onItemClick(item, { ...resource, fromContextMenu: true } as ContextMenuResource);
59 const mergeProps = ({ resource, ...dataProps }: DataProps, actionProps: ActionProps): ContextMenuProps => ({
62 onItemClick: handleItemClick(resource, actionProps.onItemClick),
65 export const ContextMenu = connect(mapStateToProps, mapDispatchToProps, mergeProps)(ContextMenuComponent);
67 const menuActionSets = new Map<string, ContextMenuActionSet>();
69 export const addMenuActionSet = (name: ContextMenuKind, itemSet: ContextMenuActionSet) => {
70 const sorted = itemSet.map(items => sortMenuItems(name, items));
71 menuActionSets.set(name, sorted);
74 const emptyActionSet: ContextMenuActionSet = [];
75 const getMenuActionSet = (resource?: ContextMenuResource): ContextMenuActionSet =>
76 resource ? menuActionSets.get(resource.menuKind) || emptyActionSet : emptyActionSet;