1
0

tui.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // TODO(chart): dynamically render charts to fit height on not set
  2. //
  3. // TODO(styling): allow end user to define their own styles when hacking.
  4. //
  5. // Pingo defines an extensible TUI based on the bubbletea framework (v2). An
  6. // executable entry point is defined via cmd/pingo.go. For more on this topic,
  7. // see the Readme.
  8. //
  9. // The pingo TUI is a fully fledged and extensible "bubble" (read: widget) that
  10. // can be fully implemented as an element in further terminal applications.
  11. //
  12. // NOTE: the bubbletea framework and subsequent "bubble" concept are beyond the
  13. // scope of this documentation. For more, see the Readme.
  14. //
  15. // Pingo defines a constructor function for the Model. It takes three arguments:
  16. //
  17. // - addresses([]string): the hosts to ping. The length must be greater than
  18. // or equal to 1
  19. //
  20. // - speed(time.Duration): the polling interval
  21. //
  22. // - chartHeight(int): the desired height of the resulting charts. This
  23. // argument is integral to ensuring desired rendering of charts, when
  24. // displaying multiple hosts.
  25. //
  26. // NOTE: if chartHeight is 0, the chart will render to Model.Height
  27. //
  28. // NOTE: chartHeight is ignored when only one address or host is provided
  29. //
  30. // For more, please please see InitialModel()
  31. //
  32. // Pingo defines two bubbletea.Cmd functions:
  33. //
  34. // - Model.Tick() tea.Cmd: emits a bubbletea.TickMsg after the time.Duration
  35. // specified via Model.UpdateSpeed
  36. //
  37. // NOTE: Model.Tick() is optional. If you choose not to use Model.Tick(),
  38. // it is recommended to enforce some minimum rate mechanism for calling
  39. // Poll(). Some servers maintain a ping rate limit, and is is possible to
  40. // exceed this rate trivially with the Poll() function. (Trust us, we know
  41. // from experience)
  42. //
  43. // NOTE: Model.Tick() is automatically emit by Model.Init() - therefore,
  44. // you can control the timing of polling by overloading the Init function.
  45. //
  46. // - Model.Poll() tea.Msg: used to asynchronously call all Model.Addresses.Poll()
  47. // functions.
  48. //
  49. // NOTE: Model.Poll() is automatically injected into the Model.Update()
  50. // life cycle after Model.Tick() resolves by Model.Update(). Functionally,
  51. // this means you can omit either Model.Tick() or Model.Poll(), respectively.
  52. //
  53. // For more, see the Readme or ./examples
  54. package pingo
  55. import (
  56. "fmt"
  57. "slices"
  58. "time"
  59. "charm.land/bubbles/v2/viewport"
  60. tea "charm.land/bubbletea/v2"
  61. "charm.land/lipgloss/v2"
  62. "github.com/NimbleMarkets/ntcharts/linechart/streamlinechart"
  63. )
  64. // Style Definitions
  65. var (
  66. // A style for chart headers
  67. headerStyle = lipgloss.NewStyle().
  68. Bold(true).
  69. Italic(true)
  70. // A style for info text
  71. infoStyle = lipgloss.NewStyle().
  72. Italic(true).
  73. Faint(true)
  74. // A style for the secondary colour
  75. secondaryColor = lipgloss.NewStyle().
  76. Foreground(lipgloss.Color("#7b2d26"))
  77. // A style for the primary colour
  78. // primaryColor = lipgloss.NewStyle().
  79. // Foreground(lipgloss.Color("#f0f3f5"))
  80. // A style for handling center-aligning
  81. blockStyle = lipgloss.NewStyle().
  82. Align(lipgloss.Center)
  83. // borderStyle = lipgloss.NewStyle().
  84. // BorderForeground(lipgloss.Color("8")).
  85. // // Padding(1, 2).
  86. // BorderStyle(lipgloss.NormalBorder())
  87. // footer styles
  88. titleStyle = lipgloss.NewStyle().
  89. Align(lipgloss.Center). // implies consumer functions will apply a width
  90. Italic(true).
  91. Faint(true)
  92. // footer style
  93. footerStyle = lipgloss.NewStyle().
  94. Align(lipgloss.Center). // implies consumer functions will apply a width
  95. Italic(true).
  96. Faint(true)
  97. )
  98. type ( // tea.Msg signatures
  99. tickMsg time.Time
  100. pollResultMsg struct {
  101. results []float64
  102. index int
  103. err error
  104. }
  105. )
  106. // Bubbletea model
  107. type Model struct {
  108. Addresses []Address // as defined in internal/tui/types.go
  109. viewport viewport.Model // mark: opinionated render
  110. UpdateSpeed time.Duration
  111. ChartHeight int
  112. Height int
  113. Width int
  114. }
  115. func InitialModel(addresses []string, speed time.Duration, chartHeight int) Model {
  116. var model Model
  117. model.viewport.MouseWheelEnabled = true // mark: opinionated render
  118. model.UpdateSpeed = speed
  119. model.ChartHeight = chartHeight
  120. for _, address := range addresses {
  121. var addr Address
  122. addr.MaxResults = 80
  123. addr.Address = address
  124. model.Addresses = append(model.Addresses, addr)
  125. }
  126. return model
  127. }
  128. func (m Model) Init() tea.Cmd {
  129. return m.Tick()
  130. }
  131. func (m Model) Tick() tea.Cmd {
  132. return tea.Tick(time.Millisecond*m.UpdateSpeed, func(t time.Time) tea.Msg {
  133. return tickMsg(t)
  134. })
  135. }
  136. func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // mark: opinionated render
  137. var cmd tea.Cmd
  138. var cmds []tea.Cmd
  139. switch msg := msg.(type) {
  140. // if case is KeyMsg (keypress)
  141. case tea.WindowSizeMsg: // mark: opinionated render
  142. if m.Width == 0 && m.Height == 0 {
  143. m.viewport = viewport.New(
  144. viewport.WithHeight(10),
  145. viewport.WithWidth(msg.Width),
  146. )
  147. }
  148. m.Width = msg.Width
  149. m.Height = msg.Height
  150. for i, address := range m.Addresses {
  151. address.MaxResults = m.Width
  152. m.Addresses[i] = address
  153. }
  154. m.viewport.SetHeight(m.Height - m.getVerticalMargin())
  155. m.viewport.SetWidth(m.Width)
  156. m.viewport.YPosition = 1
  157. case tea.KeyPressMsg: // mark: opinionated render
  158. if k := msg.String(); k == "j" { // scroll down
  159. m.viewport.ScrollDown(1)
  160. } else if k == "k" { // scroll up
  161. m.viewport.ScrollUp(1)
  162. } else {
  163. if k == "ctrl+c" {
  164. cmds = append(cmds, tea.Quit)
  165. }
  166. }
  167. case tickMsg:
  168. cmds = append(cmds, m.Tick(), m.Poll())
  169. case pollResultMsg:
  170. m.Addresses[msg.index].Results = msg.results
  171. }
  172. m.viewport.SetContent(m.Render())
  173. m.viewport, cmd = m.viewport.Update(msg)
  174. cmds = append(cmds, cmd)
  175. // cmds = append(cmds, m.Poll)
  176. return m, tea.Batch(cmds...)
  177. }
  178. func (m Model) View() tea.View { // mark: opinionated render
  179. content := fmt.Sprintf("%s%s\n%s", m.header(), m.viewport.View(), m.footer())
  180. var v tea.View
  181. v.SetContent(content)
  182. v.AltScreen = true
  183. return v
  184. }
  185. func (m Model) Render() string { // mark: opinionated render
  186. var output string
  187. for _, address := range m.Addresses {
  188. if len(address.Results) == 0 {
  189. output = output + fmt.Sprintf("\n%s\tloading...", headerStyle.Render(address.Address))
  190. } else if m.Width != 0 && m.Height != 0 {
  191. if slices.Contains(address.Results, -1) {
  192. output = output + blockStyle.Width(m.Width).Render(headerStyle.Render(
  193. fmt.Sprintf("\n%s\t%s",
  194. secondaryColor.Render(address.Address),
  195. infoStyle.Render("(connection unstable)"),
  196. ),
  197. ))
  198. } else {
  199. output = output + fmt.Sprintf("\n%s",
  200. blockStyle.Width(m.Width).Render(headerStyle.Render(address.Address)))
  201. }
  202. // Linechart
  203. // set chartHeight - vertical margin
  204. chartHeight := m.Height - m.getVerticalMargin()
  205. var slc streamlinechart.Model
  206. if m.ChartHeight == 0 && len(m.Addresses) == 1 { // catch user specified fullscreen
  207. // render chart at fullscreen
  208. slc = streamlinechart.New(m.Width, chartHeight)
  209. } else if m.ChartHeight == 0 && len(m.Addresses) > 1 { // catch user specified fullscreen
  210. // render chart at fullscreen minus a few lines to hint at scrolling
  211. slc = streamlinechart.New(m.Width, chartHeight-5)
  212. } else {
  213. slc = streamlinechart.New(m.Width, m.ChartHeight)
  214. }
  215. for _, v := range address.Results {
  216. slc.Push(v)
  217. }
  218. slc.Draw()
  219. output = output + fmt.Sprintf("\n%s", slc.View())
  220. }
  221. }
  222. return output
  223. }
  224. func (m Model) header() string { return titleStyle.Width(m.Width).Render("pingo v0") } // mark: opinionated render
  225. func (m Model) footer() string { // mark: opinionated render
  226. return footerStyle.Width(m.Width).Render("j/k: down/up\t|\tq/ctrl-c/esc: quit")
  227. }
  228. func (m Model) getVerticalMargin() int { return lipgloss.Height(m.header() + m.footer()) } // mark: opinionated render
  229. // Returns a batched set of tea.Cmd functions for each address.
  230. func (m Model) Poll() tea.Cmd {
  231. var cmds []tea.Cmd
  232. for i, element := range m.Addresses {
  233. cmds = append(cmds, func() tea.Msg {
  234. results, err := element.Poll()
  235. return pollResultMsg{results: results, err: err, index: i}
  236. })
  237. }
  238. return tea.Batch(cmds...)
  239. }