Reconciled Form.focusedElement with actual focus. Fixes #922

This commit is contained in:
Oliver 2023-11-26 13:35:32 +01:00
parent 7c9e464bac
commit b11bfc7683
1 changed files with 33 additions and 6 deletions

39
form.go
View File

@ -206,13 +206,40 @@ func (f *Form) SetButtonDisabledStyle(style tcell.Style) *Form {
// non-button items first and buttons last. Note that this index is only used // non-button items first and buttons last. Note that this index is only used
// when the form itself receives focus. // when the form itself receives focus.
func (f *Form) SetFocus(index int) *Form { func (f *Form) SetFocus(index int) *Form {
if index < 0 { var current, future int
f.focusedElement = 0 for itemIndex, item := range f.items {
} else if index >= len(f.items)+len(f.buttons) { if itemIndex == index {
f.focusedElement = len(f.items) + len(f.buttons) future = itemIndex
} else {
f.focusedElement = index
} }
if item.HasFocus() {
current = itemIndex
}
}
for buttonIndex, button := range f.buttons {
if buttonIndex+len(f.items) == index {
future = buttonIndex + len(f.items)
}
if button.HasFocus() {
current = buttonIndex + len(f.items)
}
}
var focus func(p Primitive)
focus = func(p Primitive) {
p.Focus(focus)
}
if current != future {
if current >= 0 && current < len(f.items) {
f.items[current].Blur()
} else if current >= len(f.items) && current < len(f.items)+len(f.buttons) {
f.buttons[current-len(f.items)].Blur()
}
if future >= 0 && future < len(f.items) {
focus(f.items[future])
} else if future >= len(f.items) && future < len(f.items)+len(f.buttons) {
focus(f.buttons[future-len(f.items)])
}
}
f.focusedElement = future
return f return f
} }