keys.go 2.0 KB

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