Skip to content

Instantly share code, notes, and snippets.

@tsak
Created July 7, 2020 12:43
Show Gist options
  • Save tsak/49e54b7122409f289fb6d10cd19cfda1 to your computer and use it in GitHub Desktop.
Save tsak/49e54b7122409f289fb6d10cd19cfda1 to your computer and use it in GitHub Desktop.
package ui
import (
"github.com/gdamore/tcell"
"github.com/rivo/tview"
)
// FormHeader represents a header in a form to logically separate groups of elements
type FormHeader struct {
*tview.Box
label string
labelWidth int
textColor tcell.Color
finished func(tcell.Key)
}
func NewFormHeader(label string) *FormHeader {
return &FormHeader{
Box: tview.NewBox(),
label: label,
textColor: tview.Styles.PrimaryTextColor,
}
}
func (f FormHeader) GetLabel() string {
return f.label
}
func (f *FormHeader) SetFormAttributes(labelWidth int, _, _, fieldTextColor, _ tcell.Color) tview.FormItem {
f.labelWidth = labelWidth
f.textColor = fieldTextColor
return f
}
func (f FormHeader) GetFieldWidth() int {
return 1
}
func (f *FormHeader) SetFinishedFunc(handler func(key tcell.Key)) tview.FormItem {
f.finished = handler
return f
}
// Draw draws this primitive onto the screen.
func (f *FormHeader) Draw(screen tcell.Screen) {
f.Box.Draw(screen)
// Prepare
x, y, width, height := f.GetInnerRect()
rightLimit := x + width
if height < 1 || rightLimit <= x {
return
}
// Draw label.
if f.labelWidth > 0 {
labelWidth := f.labelWidth
if labelWidth > rightLimit-x {
labelWidth = rightLimit - x
}
tview.Print(screen, f.label, x, y, labelWidth, tview.AlignLeft, f.textColor)
x += labelWidth
} else {
_, drawnWidth := tview.Print(screen, f.label, x, y, rightLimit-x, tview.AlignLeft, f.textColor)
x += drawnWidth
}
}
// InputHandler returns the handler for this primitive.
// TODO: Currently this still grabs the focus and is not being skipped
func (f *FormHeader) InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
return f.WrapInputHandler(nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment