api.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package shortcuts
  3. import (
  4. "fmt"
  5. "kitty/tools/tui/loop"
  6. "strings"
  7. )
  8. var _ = fmt.Print
  9. type ShortcutMap[T comparable] struct {
  10. leaves map[string]T
  11. children map[string]*ShortcutMap[T]
  12. }
  13. func (self *ShortcutMap[T]) ResolveKeyEvent(k *loop.KeyEvent, pending_keys ...string) (ac T, pending string) {
  14. q := self
  15. for _, pk := range pending_keys {
  16. q = self.children[pk]
  17. if q == nil {
  18. return
  19. }
  20. }
  21. for c, ans := range q.leaves {
  22. if k.MatchesPressOrRepeat(c) {
  23. ac = ans
  24. return
  25. }
  26. }
  27. for c := range q.children {
  28. if k.MatchesPressOrRepeat(c) {
  29. pending = c
  30. return
  31. }
  32. }
  33. return
  34. }
  35. func (self *ShortcutMap[T]) Add(ac T, keys ...string) (conflict T) {
  36. return self.add(ac, keys)
  37. }
  38. func (self *ShortcutMap[T]) AddOrPanic(ac T, keys ...string) {
  39. var zero T
  40. c := self.add(ac, keys)
  41. if c != zero {
  42. panic(fmt.Sprintf("The shortcut for %#v (%s) conflicted with the shortcut for %#v (%s)",
  43. ac, strings.Join(keys, " "), c, strings.Join(self.shortcut_for(c), " ")))
  44. }
  45. }
  46. func New[T comparable]() *ShortcutMap[T] {
  47. return &ShortcutMap[T]{leaves: make(map[string]T), children: make(map[string]*ShortcutMap[T])}
  48. }