Add an optional onCancel hook for menus

This commit is contained in:
Stefan Haller 2026-03-24 17:28:35 +01:00
parent 7a0320b4ec
commit 28affa3399
3 changed files with 13 additions and 0 deletions

View file

@ -57,6 +57,7 @@ type MenuViewModel struct {
columnAlignment []utils.Alignment
allowFilteringKeybindings bool
keybindingsTakePrecedence bool
onCancel func() error
*FilteredListViewModel[*types.MenuItem]
}
@ -97,6 +98,10 @@ func (self *MenuViewModel) SetMenuItems(items []*types.MenuItem, columnAlignment
self.columnAlignment = columnAlignment
}
func (self *MenuViewModel) SetOnCancel(onCancel func() error) {
self.onCancel = onCancel
}
func (self *MenuViewModel) GetPrompt() string {
return self.prompt
}
@ -239,6 +244,9 @@ func (self *MenuContext) OnMenuPress(selectedItem *types.MenuItem) error {
self.c.Context().Pop()
if selectedItem == nil {
if self.onCancel != nil {
return self.onCancel()
}
return nil
}

View file

@ -16,6 +16,9 @@ func (gui *Gui) createMenu(opts types.CreateMenuOptions) error {
opts.Items = append(opts.Items, &types.MenuItem{
LabelColumns: []string{gui.c.Tr.Cancel},
OnPress: func() error {
if opts.OnCancel != nil {
return opts.OnCancel()
}
return nil
},
})
@ -59,6 +62,7 @@ func (gui *Gui) createMenu(opts types.CreateMenuOptions) error {
gui.State.Contexts.Menu.SetPrompt(opts.Prompt)
gui.State.Contexts.Menu.SetAllowFilteringKeybindings(opts.AllowFilteringKeybindings)
gui.State.Contexts.Menu.SetKeybindingsTakePrecedence(!opts.KeepConflictingKeybindings)
gui.State.Contexts.Menu.SetOnCancel(opts.OnCancel)
gui.State.Contexts.Menu.SetSelection(0)
gui.Views.Menu.SetOriginY(0)

View file

@ -154,6 +154,7 @@ type CreateMenuOptions struct {
Prompt string // a message that will be displayed above the menu options
Items []*MenuItem
HideCancel bool
OnCancel func() error // called when the menu is dismissed without selecting an item
ColumnAlignment []utils.Alignment
AllowFilteringKeybindings bool
KeepConflictingKeybindings bool // if true, the keybindings that match essential bindings such as confirm or return will not be removed from menu items