Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions key/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
// to render help text for keystrokes in your views.
package key

import "fmt"
import (
"fmt"

tea "github.com/charmbracelet/bubbletea/v2"
)

// Binding describes a set of keybindings and, optionally, their associated
// help text.
Expand Down Expand Up @@ -128,10 +132,15 @@ type Help struct {

// Matches checks if the given key matches the given bindings.
func Matches[Key fmt.Stringer](k Key, b ...Binding) bool {
var txt string
switch v := any(k).(type) {
case tea.KeyMsg:
txt = v.Key().Text
}
keys := k.String()
for _, binding := range b {
for _, v := range binding.keys {
if keys == v && binding.Enabled() {
if binding.Enabled() && (v == keys || (txt != "" && v == txt)) {
return true
}
}
Expand Down
43 changes: 43 additions & 0 deletions key/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package key

import (
"testing"

tea "github.com/charmbracelet/bubbletea/v2"
)

func TestBinding_Enabled(t *testing.T) {
Expand All @@ -24,3 +26,44 @@ func TestBinding_Enabled(t *testing.T) {
t.Errorf("expected key not to be Enabled")
}
}

func TestMatches(t *testing.T) {
cases := []struct {
key tea.KeyMsg
bindings []Binding
}{
{
key: tea.KeyPressMsg{Code: 'k', Text: "k"},
bindings: []Binding{
NewBinding(
WithKeys("k", "up"),
WithHelp("↑/k", "move up"),
),
},
},
{
key: tea.KeyPressMsg{Code: '/', Mod: tea.ModShift, Text: "?"},
bindings: []Binding{
NewBinding(
WithKeys("?"),
WithHelp("?", "search"),
),
},
},
{
key: tea.KeyPressMsg{Code: 'a', Mod: tea.ModCtrl},
bindings: []Binding{
NewBinding(
WithKeys("ctrl+a"),
WithHelp("ctrl+a", "select all"),
),
},
},
}

for i, c := range cases {
if !Matches(c.key, c.bindings...) {
t.Errorf("case %d: expected key (%q) to match binding(s)", i+1, c.key.String())
}
}
}
Loading