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