From 28affa3399852c435b443fc37697a87a9ec8ccbe Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 24 Mar 2026 17:28:35 +0100 Subject: [PATCH] Add an optional onCancel hook for menus --- pkg/gui/context/menu_context.go | 8 ++++++++ pkg/gui/menu_panel.go | 4 ++++ pkg/gui/types/common.go | 1 + 3 files changed, 13 insertions(+) diff --git a/pkg/gui/context/menu_context.go b/pkg/gui/context/menu_context.go index 097812614..ced9666f9 100644 --- a/pkg/gui/context/menu_context.go +++ b/pkg/gui/context/menu_context.go @@ -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 } diff --git a/pkg/gui/menu_panel.go b/pkg/gui/menu_panel.go index b100a4beb..4c6a44667 100644 --- a/pkg/gui/menu_panel.go +++ b/pkg/gui/menu_panel.go @@ -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) diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index b9e7cc9c8..06c459add 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -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