rivo / tview

Terminal UI library with rich, interactive widgets — written in Golang
MIT License
10.33k stars 545 forks source link

How to make a popup box #994

Closed benstigsen closed 1 month ago

benstigsen commented 1 month ago

It is unclear to me how you create something like a popup box that contains elements like text, buttons, input fields and so on.

I currently have a list of items like this:

package main

import (
    "github.com/rivo/tview"
)

func main() {
    list := tview.NewList()
    list.AddItem("Item 1", "", 0, func() {
        // open box with elements on top of the list, but still showing the list in the background
    })
    if err := tview.NewApplication().SetRoot(list, true).Run(); err != nil {
        panic(err)
    }
}

How I make something appear on top of what's already there is very unclear to me. Pages seems to be the way to do it, but I just don't get how.

image

sjsanc commented 1 month ago

The second example in the modals primitive wiki page can be modified to achieve this effect.

import (
    "github.com/rivo/tview"
)

func main() {
    app := tview.NewApplication()

    modal := func(p tview.Primitive, width, height int) tview.Primitive {
        return tview.NewFlex().
            AddItem(nil, 0, 1, false).
            AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
                AddItem(nil, 0, 1, false).
                AddItem(p, height, 1, true).
                AddItem(nil, 0, 1, false), width, 1, true).
            AddItem(nil, 0, 1, false)
    }

    pages := tview.NewPages()

    button := tview.NewButton("Close modal").SetSelectedFunc(func() {
        pages.RemovePage("modal")
    })

    list := tview.NewList().
        AddItem("Open Modal", "Click top open modal", '1', func() {
            pages.AddPage("modal", modal(button, 40, 10), true, true)
        }).
        AddItem("Quit", "Press to exit", 'q', func() {
            app.Stop()
        })

    pages.AddPage("main", list, true, true)

    if err := app.SetRoot(pages, true).Run(); err != nil {
        panic(err)
    }
}

2024-05-29_14-23

benstigsen commented 1 month ago

Yep that works, thank you!