This repository has been archived on 2021-03-25. You can view files and clone it, but cannot push or open issues/pull-requests.
tui/menu.go

62 lines
1.1 KiB
Go

package tui
import "strings"
func GetMenu(
title string,
text string,
items ...string, // key -> value pairs
) string {
keys := map[string]bool{}
keyWidth := 0
for i := 0; i < len(items); i += 2 {
key := items[i]
keyLen := len([]rune(key))
keys[items[i]] = true
if keyLen > keyWidth {
keyWidth = keyLen
}
}
drawMenu := func() {
Clear()
PrintBoxed(title)
PrintString("┆")
if text != "" {
PrintTextWithPrefix("│ ", text)
PrintString("│")
}
w, _ := termSize()
valWidth := w - keyWidth - 5
for i := 0; i < len(items); i += 2 {
key := items[i]
keyLen := len([]rune(key))
text := items[i+1]
lines, _ := wrapText(text, valWidth)
indent := keyWidth - keyLen
// First line.
sIndent := strings.Repeat(" ", indent)
PrintString("│ %s%s %s", key, sIndent, lines[0])
// Additional lines.
for _, line := range lines[1:] {
sIndent := strings.Repeat(" ", keyWidth)
PrintString("│ %s %s", sIndent, line)
}
}
PrintString("│")
}
for {
drawMenu()
in := GetString("╰─┄ ")
if _, ok := keys[in]; ok {
return in
}
}
}