keys.go

  1package tui
  2
  3import (
  4	"github.com/charmbracelet/bubbles/v2/key"
  5)
  6
  7type KeyMap struct {
  8	Logs     key.Binding
  9	Quit     key.Binding
 10	Help     key.Binding
 11	Commands key.Binding
 12	Sessions key.Binding
 13
 14	pageBindings []key.Binding
 15}
 16
 17func DefaultKeyMap() KeyMap {
 18	return KeyMap{
 19		Logs: key.NewBinding(
 20			key.WithKeys("ctrl+l"),
 21			key.WithHelp("ctrl+l", "logs"),
 22		),
 23		Quit: key.NewBinding(
 24			key.WithKeys("ctrl+c"),
 25			key.WithHelp("ctrl+c", "quit"),
 26		),
 27		Help: key.NewBinding(
 28			key.WithKeys("ctrl+?", "ctrl+_", "ctrl+/"),
 29			key.WithHelp("ctrl+?", "more"),
 30		),
 31		Commands: key.NewBinding(
 32			key.WithKeys("ctrl+p"),
 33			key.WithHelp("ctrl+p", "commands"),
 34		),
 35		Sessions: key.NewBinding(
 36			key.WithKeys("ctrl+s"),
 37			key.WithHelp("ctrl+s", "sessions"),
 38		),
 39	}
 40}
 41
 42// FullHelp implements help.KeyMap.
 43func (k KeyMap) FullHelp() [][]key.Binding {
 44	m := [][]key.Binding{}
 45	slice := []key.Binding{
 46		k.Commands,
 47		k.Sessions,
 48		k.Quit,
 49		k.Help,
 50		k.Logs,
 51	}
 52	slice = k.prependEscAndTab(slice)
 53	slice = append(slice, k.pageBindings...)
 54	// remove duplicates
 55	seen := make(map[string]bool)
 56	cleaned := []key.Binding{}
 57	for _, b := range slice {
 58		if !seen[b.Help().Key] {
 59			seen[b.Help().Key] = true
 60			cleaned = append(cleaned, b)
 61		}
 62	}
 63
 64	for i := 0; i < len(cleaned); i += 3 {
 65		end := min(i+3, len(cleaned))
 66		m = append(m, cleaned[i:end])
 67	}
 68	return m
 69}
 70
 71func (k KeyMap) prependEscAndTab(bindings []key.Binding) []key.Binding {
 72	var cancel key.Binding
 73	var tab key.Binding
 74	for _, b := range k.pageBindings {
 75		if b.Help().Key == "esc" {
 76			cancel = b
 77		}
 78		if b.Help().Key == "tab" {
 79			tab = b
 80		}
 81	}
 82	if tab.Help().Key != "" {
 83		bindings = append([]key.Binding{tab}, bindings...)
 84	}
 85	if cancel.Help().Key != "" {
 86		bindings = append([]key.Binding{cancel}, bindings...)
 87	}
 88	return bindings
 89}
 90
 91// ShortHelp implements help.KeyMap.
 92func (k KeyMap) ShortHelp() []key.Binding {
 93	bindings := []key.Binding{
 94		k.Commands,
 95		k.Sessions,
 96		k.Quit,
 97		k.Help,
 98	}
 99	return k.prependEscAndTab(bindings)
100}