Context Menus
Context menus are supported by both GraphEditorInputMode and GraphViewerInputMode.
You can open and populate a context menu in a handler for
the populate-item-context-menu event of GraphEditorInputMode or GraphViewerInputMode.
This event occurs after the user has requested a context menu, but before
the menu is displayed.
This allows you to create context menus that are contextual to the item
that was right-clicked by populating the context menu with ContextMenuContent
s appropriate for that item:
// handle context menus only for nodes
graphEditorInputMode.contextMenuItems = GraphItemTypes.NODE
// register a listener for populating the menu
graphEditorInputMode.addEventListener(
'populate-item-context-menu',
populateItemContextMenuCallback
)
In the callback, the context menu can be assigned to the contextMenu property.
It can either be a custom HTMLElement
, for example, from a UI framework or an Array
containing
Object
s that describe the label and action of a context menu:
function populateItemContextMenuCallback(event) {
if (event.handled) {
// the event is already handled, there is nothing to do
return
}
if (event.item instanceof INode) {
// show the menu only for nodes
event.contextMenu = [
{
label: 'Delete Node',
action: () => graphComponent.graph.remove(event.item)
}
]
// and mark the event as handled
event.handled = true
}
}
function populateItemContextMenuCallback(
event: PopulateItemContextMenuEventArgs<IModelItem>
): void {
if (event.handled) {
// the event is already handled, there is nothing to do
return
}
if (event.item instanceof INode) {
// show the menu only for nodes
event.contextMenu = [
{
label: 'Delete Node',
action: () => graphComponent.graph.remove(event.item!)
}
]
// and mark the event as handled
event.handled = true
}
}
The contextMenuItems property on GraphEditorInputMode and GraphViewerInputMode determines for which items the context menu events will trigger when clicked. You can make a more specific distinction per item by setting a custom populateContextMenuPredicate.
The ContextMenuInputMode does the actual work and is a child input mode for both GraphEditorInputMode and GraphViewerInputMode.
You can further customize the ContextMenuInputMode. GraphEditorInputMode and GraphViewerInputMode trigger the populate-item-context-menu event upon the populate-menu event of the ContextMenuInputMode. For more customization, you can override the dispatching method, onPopulateMenu.
- validMenuLocationHitTestable
- Specifies the area in which a context menu can be requested.