subsonic-tui/internal/tui/views/status_line.go
Sagi Dayan 26e526f07e
initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-02-20 19:10:14 +02:00

94 lines
1.7 KiB
Go

package views
import (
"fmt"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
var _ View = &statusLine{}
type statusLine struct {
view *tview.Flex
mode Statusmode
onUpdateFunc func()
onSearchFunc func(quary string)
}
type Statusmode int
const (
StatusModeLog Statusmode = iota
StatusModeSearch Statusmode = iota
)
func NewStatusLine() *statusLine {
status := tview.NewFlex()
// Default empty box
status.AddItem(tview.NewBox(), 0, 1, false)
return &statusLine{
view: status,
mode: StatusModeLog,
}
}
func (s *statusLine) SetSearchFunc(f func(quary string)) {
s.onSearchFunc = f
}
func (s *statusLine) Mode() Statusmode {
return s.mode
}
func (s *statusLine) Search() {
s.mode = StatusModeSearch
s.view.Clear()
label := "Search: "
_, _, w, _ := s.view.GetRect()
query := ""
inputField := tview.NewInputField()
inputField.
SetLabel(label).
SetFieldWidth(w - len(label)).
SetDoneFunc(func(key tcell.Key) {
if key == tcell.KeyEnter {
s.mode = StatusModeLog
s.onSearchFunc(query)
} else if key == tcell.KeyEsc {
s.mode = StatusModeLog
s.onSearchFunc("")
}
}).
SetChangedFunc(func(text string) {
query = text
})
inputField.Focus(nil)
s.view.AddItem(inputField, 0, 1, true)
s.Update()
}
func (s *statusLine) SetOnUpdateFunc(f func()) {
s.onUpdateFunc = f
}
func (s *statusLine) Log(format string, a ...any) {
if s.mode != StatusModeLog {
return
}
str := fmt.Sprintf(format, a...)
s.view.Clear()
txt := tview.NewTextView().SetDynamicColors(true)
txt.SetText(str)
s.view.AddItem(txt, 0, 1, false)
s.Update()
}
func (s *statusLine) GetView() tview.Primitive {
return s.view
}
func (s *statusLine) Update() {
s.onUpdateFunc()
}