1
0

tui.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package tui
  2. import (
  3. "fmt"
  4. tea "github.com/charmbracelet/bubbletea"
  5. )
  6. // Bubbletea model
  7. //
  8. // BUG(state): how do declare pointer here?
  9. type Model struct {
  10. Addresses []Address // as defined in internal/tui/types.go
  11. }
  12. func InitialModel(addresses []string) Model {
  13. var model Model
  14. for _, address := range addresses {
  15. var addr Address
  16. addr.Address = address
  17. model.Addresses = append(model.Addresses, addr)
  18. }
  19. return model
  20. }
  21. func (m Model) Init() tea.Cmd {
  22. return m.Poll
  23. }
  24. func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  25. switch msg.(type) {
  26. // if case is KeyMsg (keypress)
  27. case tea.KeyMsg:
  28. return m, tea.Quit
  29. // switch msg.String() {
  30. // case "ctrl+c", "q": // These keys should exit the program.
  31. // return m, tea.Quit
  32. // }
  33. case pollMsg:
  34. m.Poll()
  35. }
  36. return m, m.Poll
  37. }
  38. // A wrapper for the underlying [tui.Address.Poll] function. For each address in
  39. // [tui.Model.Addresses], run its respective Poll function and update [tui.Model]
  40. //
  41. // NOTE(async): this function fully blocks execution of the current thread.
  42. func (m Model) Poll() tea.Msg {
  43. for i, element := range m.Addresses {
  44. element.Poll()
  45. m.Addresses[i] = element
  46. }
  47. return true
  48. }
  49. func (m Model) View() string {
  50. output := "Results:\n"
  51. for _, address := range m.Addresses {
  52. last := address.Last()
  53. if last == -1 {
  54. output = output + fmt.Sprintf("%s: loading...\n", address.Address)
  55. } else {
  56. output = output + fmt.Sprintf("%s: %f\n", address.Address, last)
  57. }
  58. }
  59. return output
  60. }