widget.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
  2. // Use of this source code is governed by a MIT license that can
  3. // be found in the LICENSE file.
  4. package termui
  5. import (
  6. "fmt"
  7. "sync"
  8. )
  9. // event mixins
  10. type WgtMgr map[string]WgtInfo
  11. type WgtInfo struct {
  12. Handlers map[string]func(Event)
  13. WgtRef Widget
  14. Id string
  15. }
  16. type Widget interface {
  17. Id() string
  18. }
  19. func NewWgtInfo(wgt Widget) WgtInfo {
  20. return WgtInfo{
  21. Handlers: make(map[string]func(Event)),
  22. WgtRef: wgt,
  23. Id: wgt.Id(),
  24. }
  25. }
  26. func NewWgtMgr() WgtMgr {
  27. wm := WgtMgr(make(map[string]WgtInfo))
  28. return wm
  29. }
  30. func (wm WgtMgr) AddWgt(wgt Widget) {
  31. wm[wgt.Id()] = NewWgtInfo(wgt)
  32. }
  33. func (wm WgtMgr) RmWgt(wgt Widget) {
  34. wm.RmWgtById(wgt.Id())
  35. }
  36. func (wm WgtMgr) RmWgtById(id string) {
  37. delete(wm, id)
  38. }
  39. func (wm WgtMgr) AddWgtHandler(id, path string, h func(Event)) {
  40. if w, ok := wm[id]; ok {
  41. w.Handlers[path] = h
  42. }
  43. }
  44. func (wm WgtMgr) RmWgtHandler(id, path string) {
  45. if w, ok := wm[id]; ok {
  46. delete(w.Handlers, path)
  47. }
  48. }
  49. var counter struct {
  50. sync.RWMutex
  51. count int
  52. }
  53. func GenId() string {
  54. counter.Lock()
  55. defer counter.Unlock()
  56. counter.count += 1
  57. return fmt.Sprintf("%d", counter.count)
  58. }
  59. func (wm WgtMgr) WgtHandlersHook() func(Event) {
  60. return func(e Event) {
  61. for _, v := range wm {
  62. if k := findMatch(v.Handlers, e.Path); k != "" {
  63. v.Handlers[k](e)
  64. }
  65. }
  66. }
  67. }
  68. var DefaultWgtMgr WgtMgr
  69. func (b *Block) Handle(path string, handler func(Event)) {
  70. if _, ok := DefaultWgtMgr[b.Id()]; !ok {
  71. DefaultWgtMgr.AddWgt(b)
  72. }
  73. DefaultWgtMgr.AddWgtHandler(b.Id(), path, handler)
  74. }