From 745183a77f0d0b2523e90fd1dd32a9b4a3f9f6a5 Mon Sep 17 00:00:00 2001 From: Kevin Miller Date: Thu, 11 Apr 2024 10:08:39 -0500 Subject: [PATCH] navstack: close the top model when on push --- examples/deeper/artistpaintings/model.go | 5 +++++ navstack/model.go | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/examples/deeper/artistpaintings/model.go b/examples/deeper/artistpaintings/model.go index 48c6327..9dc2f95 100644 --- a/examples/deeper/artistpaintings/model.go +++ b/examples/deeper/artistpaintings/model.go @@ -42,6 +42,11 @@ func (m Model) Init() tea.Cmd { return nil } +func (m Model) Close() error { + // This is called when the model is pushed and popped from the navigation stack. + return nil +} + func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { diff --git a/navstack/model.go b/navstack/model.go index b29c718..6317fed 100644 --- a/navstack/model.go +++ b/navstack/model.go @@ -48,9 +48,17 @@ func (m Model) Init() tea.Cmd { // Push pushes a new navigation item onto the stack. // The new navigation item is given a tea.WindowSizeMsg to ensure it's view can be presented correctly. // The item's Init method is called and resulting command is processed by [BubbleTea]. +// If top item's model implements the Closable interface the Close method is called. // This new item will be the top most item on the stack and thus will be rendered. func (m *Model) Push(item NavigationItem) tea.Cmd { + top := m.Top() + if top != nil { + if c, ok := top.Model.(Closable); ok { + c.Close() + } + } + wmsg := m.window.GetWindowSizeMsg() nim, cmd := item.Model.Update(wmsg) item.Model = nim