Every redraw of a Form re-evaluates the focus index. Fixes #144

This commit is contained in:
Oliver 2019-08-29 18:12:55 +02:00
parent 23dc8a0944
commit f8bc69b903
1 changed files with 25 additions and 12 deletions

37
form.go
View File

@ -59,7 +59,8 @@ type Form struct {
itemPadding int
// The index of the item or button which has focus. (Items are counted first,
// buttons are counted last.)
// buttons are counted last.) This is only used when the form itself receives
// focus so that the last element that had focus keeps it.
focusedElement int
// The label color.
@ -345,6 +346,11 @@ func (f *Form) SetCancelFunc(callback func()) *Form {
func (f *Form) Draw(screen tcell.Screen) {
f.Box.Draw(screen)
// Determine the actual item that has focus.
if index := f.focusIndex(); index >= 0 {
f.focusedElement = index
}
// Determine the dimensions.
x, y, width, height := f.GetInnerRect()
topLimit := y
@ -575,15 +581,22 @@ func (f *Form) HasFocus() bool {
if f.hasFocus {
return true
}
for _, item := range f.items {
if item.GetFocusable().HasFocus() {
return true
}
}
for _, button := range f.buttons {
if button.focus.HasFocus() {
return true
}
}
return false
return f.focusIndex() >= 0
}
// focusIndex returns the index of the currently focused item, counting form
// items first, then buttons. A negative value indicates that no containeed item
// has focus.
func (f *Form) focusIndex() int {
for index, item := range f.items {
if item.GetFocusable().HasFocus() {
return index
}
}
for index, button := range f.buttons {
if button.focus.HasFocus() {
return len(f.items) + index
}
}
return -1
}