ads1_2021/code/golang/internal/menus/menus.go

103 lines
2.6 KiB
Go

package menus
/* ---------------------------------------------------------------- *
* IMPORTS
* ---------------------------------------------------------------- */
import (
"fmt"
"strconv"
"strings"
"ads/internal/core/logging"
)
/* ---------------------------------------------------------------- *
* METHOD show menu
* ---------------------------------------------------------------- */
func (menu Menu) ShowMenu() (bool, error) {
var (
choice string
index int
meta bool
quit bool
)
var promptMessages []string
var options [][2]string
var defaultOption string
var breaks []int
// Headline einfügen
promptMessages = make([]string, len(menu.PromptMessages))
copy(promptMessages, menu.PromptMessages)
head := fmt.Sprintf("\033[2m%s\033[0m", strings.Join(menu.Path, " > "))
promptMessages = append([]string{head}, promptMessages...)
// Zurück-Option einfügen
defaultOption = fmt.Sprintf("%v", menu.DefaultOption)
options = []([2]string){}
for i, opt := range menu.Options {
key := fmt.Sprintf("%v", i+1)
subLabel := opt.SubLabel
label := opt.Label
if !(subLabel == "") {
label = fmt.Sprintf("%v (\033[2m%v\033[0m)", opt.Label, subLabel)
}
options = append(options, [2]string{key, label})
}
breaks = []int{len(menu.Options) - 1}
if !menu.IsRoot {
options = append(options, [2]string{"z", "Zurück zum vorherigen Menü"})
}
options = append(options, [2]string{"q", "Programm schließen"})
// User Response immer abfragen und abarbeiten, bis quit/return.
performClearScreen := !menu.IsRoot
for {
if performClearScreen {
logging.ClearScreen()
}
performClearScreen = true
choice, meta = PromptListOfOptions(promptMessages, options, breaks, defaultOption)
// Falls quit wählt, -> quit:
if (menu.IsRoot && meta) || choice == "q" {
return true, nil
}
// Falls User back wählt, -> return:
if (!menu.IsRoot && meta) || choice == "z" {
return false, nil
}
// sonst führe die assoziierte Methode aus
index64, _ := strconv.ParseInt(choice, 10, 64)
index = int(index64) - 1
if 0 <= index && index < len(menu.Options) {
opt := menu.Options[index]
// Entweder Untermenü öffnen oder Action ausführen
if opt.Submenu != nil {
quit, _ = opt.Submenu.ShowMenu()
if quit {
return true, nil
}
} else if opt.Action != nil {
opt.Action()
quit := logging.PromptAnyKeyToContinue()
// Falls während der Action der User Meta+D klickt, -> quit:
if quit {
return true, nil
}
} else {
logging.LogWarn("Option noch nicht implementiert.")
quit := logging.PromptAnyKeyToContinue()
if quit {
return true, nil
}
}
}
}
}