rivo / tview

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

How to make a popup box #994

Closed benstigsen closed 6 months ago

benstigsen commented 6 months 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 6 months 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 6 months ago

Yep that works, thank you!