Skip to content

Commit 755c6d2

Browse files
author
Kevin Miller
committed
fix textinput.CurrentSuggestion() panic
When suggestions are not yet set CurrentSuggestion() will panic. This change fixes that with a guard and returns an empty string when there is no current suggestion.
1 parent fc18779 commit 755c6d2

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

textinput/textinput.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -830,7 +830,16 @@ func (m *Model) AvailableSuggestions() []string {
830830

831831
// CurrentSuggestion returns the currently selected suggestion.
832832
func (m *Model) CurrentSuggestion() string {
833-
return string(m.matchedSuggestions[m.currentSuggestionIndex])
833+
if len(m.matchedSuggestions) < 1 {
834+
return ""
835+
}
836+
837+
s := m.matchedSuggestions[m.currentSuggestionIndex]
838+
if s == nil {
839+
return ""
840+
}
841+
842+
return string(s)
834843
}
835844

836845
// canAcceptSuggestion returns whether there is an acceptable suggestion to

textinput/textinput_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package textinput
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func Test_CurrentSuggestion(t *testing.T) {
8+
textinput := New()
9+
textinput.ShowSuggestions = true
10+
11+
suggestion := textinput.CurrentSuggestion()
12+
expected := ""
13+
if suggestion != expected {
14+
t.Fatalf("Error: expected no current suggestion but was %s", suggestion)
15+
}
16+
17+
textinput.SetSuggestions([]string{"test1", "test2", "test3"})
18+
suggestion = textinput.CurrentSuggestion()
19+
expected = ""
20+
if suggestion != expected {
21+
t.Fatalf("Error: expected no current suggestion but was %s", suggestion)
22+
}
23+
24+
textinput.SetValue("test")
25+
textinput.updateSuggestions()
26+
textinput.nextSuggestion()
27+
suggestion = textinput.CurrentSuggestion()
28+
expected = "test2"
29+
if suggestion != expected {
30+
t.Fatalf("Error: expected first suggestion but was %s", suggestion)
31+
}
32+
}

0 commit comments

Comments
 (0)