| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276 |
- // TODO(chart): dynamically render charts to fit height on not set
- //
- // TODO(styling): allow end user to define their own styles when hacking.
- //
- // Pingo defines an extensible TUI based on the bubbletea framework (v2). An
- // executable entry point is defined via cmd/pingo.go. For more on this topic,
- // see the Readme.
- //
- // The pingo TUI is a fully fledged and extensible "bubble" (read: widget) that
- // can be fully implemented as an element in further terminal applications.
- //
- // NOTE: the bubbletea framework and subsequent "bubble" concept are beyond the
- // scope of this documentation. For more, see the Readme.
- //
- // Pingo defines a constructor function for the Model. It takes three arguments:
- //
- // - addresses([]string): the hosts to ping. The length must be greater than
- // or equal to 1
- //
- // - speed(time.Duration): the polling interval
- //
- // - chartHeight(int): the desired height of the resulting charts. This
- // argument is integral to ensuring desired rendering of charts, when
- // displaying multiple hosts.
- //
- // NOTE: if chartHeight is 0, the chart will render to Model.Height
- //
- // NOTE: chartHeight is ignored when only one address or host is provided
- //
- // For more, please please see InitialModel()
- //
- // Pingo defines two bubbletea.Cmd functions:
- //
- // - Model.Tick() tea.Cmd: emits a bubbletea.TickMsg after the time.Duration
- // specified via Model.UpdateSpeed
- //
- // NOTE: Model.Tick() is optional. If you choose not to use Model.Tick(),
- // it is recommended to enforce some minimum rate mechanism for calling
- // Poll(). Some servers maintain a ping rate limit, and is is possible to
- // exceed this rate trivially with the Poll() function. (Trust us, we know
- // from experience)
- //
- // NOTE: Model.Tick() is automatically emit by Model.Init() - therefore,
- // you can control the timing of polling by overloading the Init function.
- //
- // - Model.Poll() tea.Msg: used to asynchronously call all Model.Addresses.Poll()
- // functions.
- //
- // NOTE: Model.Poll() is automatically injected into the Model.Update()
- // life cycle after Model.Tick() resolves by Model.Update(). Functionally,
- // this means you can omit either Model.Tick() or Model.Poll(), respectively.
- //
- // For more, see the Readme or ./examples
- package pingo
- import (
- "fmt"
- "slices"
- "time"
- "charm.land/bubbles/v2/viewport"
- tea "charm.land/bubbletea/v2"
- "charm.land/lipgloss/v2"
- "github.com/NimbleMarkets/ntcharts/linechart/streamlinechart"
- )
- // Style Definitions
- var (
- // A style for chart headers
- headerStyle = lipgloss.NewStyle().
- Bold(true).
- Italic(true)
- // A style for info text
- infoStyle = lipgloss.NewStyle().
- Italic(true).
- Faint(true)
- // A style for the secondary colour
- secondaryColor = lipgloss.NewStyle().
- Foreground(lipgloss.Color("#7b2d26"))
- // A style for the primary colour
- // primaryColor = lipgloss.NewStyle().
- // Foreground(lipgloss.Color("#f0f3f5"))
- // A style for handling center-aligning
- blockStyle = lipgloss.NewStyle().
- Align(lipgloss.Center)
- // borderStyle = lipgloss.NewStyle().
- // BorderForeground(lipgloss.Color("8")).
- // // Padding(1, 2).
- // BorderStyle(lipgloss.NormalBorder())
- // footer styles
- titleStyle = lipgloss.NewStyle().
- Align(lipgloss.Center). // implies consumer functions will apply a width
- Italic(true).
- Faint(true)
- // footer style
- footerStyle = lipgloss.NewStyle().
- Align(lipgloss.Center). // implies consumer functions will apply a width
- Italic(true).
- Faint(true)
- )
- type ( // tea.Msg signatures
- tickMsg time.Time
- pollResultMsg struct {
- results []float64
- index int
- err error
- }
- )
- // Bubbletea model
- type Model struct {
- Addresses []Address // as defined in internal/tui/types.go
- viewport viewport.Model // mark: opinionated render
- UpdateSpeed time.Duration
- ChartHeight int
- Height int
- Width int
- }
- func InitialModel(addresses []string, speed time.Duration, chartHeight int) Model {
- var model Model
- model.viewport.MouseWheelEnabled = true // mark: opinionated render
- model.UpdateSpeed = speed
- model.ChartHeight = chartHeight
- for _, address := range addresses {
- var addr Address
- addr.MaxResults = 80
- addr.Address = address
- model.Addresses = append(model.Addresses, addr)
- }
- return model
- }
- func (m Model) Init() tea.Cmd {
- return m.Tick()
- }
- func (m Model) Tick() tea.Cmd {
- return tea.Tick(time.Millisecond*m.UpdateSpeed, func(t time.Time) tea.Msg {
- return tickMsg(t)
- })
- }
- func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // mark: opinionated render
- var cmd tea.Cmd
- var cmds []tea.Cmd
- switch msg := msg.(type) {
- // if case is KeyMsg (keypress)
- case tea.WindowSizeMsg: // mark: opinionated render
- if m.Width == 0 && m.Height == 0 {
- m.viewport = viewport.New(
- viewport.WithHeight(10),
- viewport.WithWidth(msg.Width),
- )
- }
- m.Width = msg.Width
- m.Height = msg.Height
- for i, address := range m.Addresses {
- address.MaxResults = m.Width
- m.Addresses[i] = address
- }
- m.viewport.SetHeight(m.Height - m.getVerticalMargin())
- m.viewport.SetWidth(m.Width)
- m.viewport.YPosition = 1
- case tea.KeyPressMsg: // mark: opinionated render
- if k := msg.String(); k == "j" { // scroll down
- m.viewport.ScrollDown(1)
- } else if k == "k" { // scroll up
- m.viewport.ScrollUp(1)
- } else {
- if k == "ctrl+c" {
- cmds = append(cmds, tea.Quit)
- }
- }
- case tickMsg:
- cmds = append(cmds, m.Tick(), m.Poll())
- case pollResultMsg:
- m.Addresses[msg.index].Results = msg.results
- }
- m.viewport.SetContent(m.Render())
- m.viewport, cmd = m.viewport.Update(msg)
- cmds = append(cmds, cmd)
- // cmds = append(cmds, m.Poll)
- return m, tea.Batch(cmds...)
- }
- func (m Model) View() tea.View { // mark: opinionated render
- content := fmt.Sprintf("%s%s\n%s", m.header(), m.viewport.View(), m.footer())
- var v tea.View
- v.SetContent(content)
- v.AltScreen = true
- return v
- }
- func (m Model) Render() string { // mark: opinionated render
- var output string
- for _, address := range m.Addresses {
- if len(address.Results) == 0 {
- output = output + fmt.Sprintf("\n%s\tloading...", headerStyle.Render(address.Address))
- } else if m.Width != 0 && m.Height != 0 {
- if slices.Contains(address.Results, -1) {
- output = output + blockStyle.Width(m.Width).Render(headerStyle.Render(
- fmt.Sprintf("\n%s\t%s",
- secondaryColor.Render(address.Address),
- infoStyle.Render("(connection unstable)"),
- ),
- ))
- } else {
- output = output + fmt.Sprintf("\n%s",
- blockStyle.Width(m.Width).Render(headerStyle.Render(address.Address)))
- }
- // Linechart
- // set chartHeight - vertical margin
- chartHeight := m.Height - m.getVerticalMargin()
- var slc streamlinechart.Model
- if m.ChartHeight == 0 && len(m.Addresses) == 1 { // catch user specified fullscreen
- // render chart at fullscreen
- slc = streamlinechart.New(m.Width, chartHeight)
- } else if m.ChartHeight == 0 && len(m.Addresses) > 1 { // catch user specified fullscreen
- // render chart at fullscreen minus a few lines to hint at scrolling
- slc = streamlinechart.New(m.Width, chartHeight-5)
- } else {
- slc = streamlinechart.New(m.Width, m.ChartHeight)
- }
- for _, v := range address.Results {
- slc.Push(v)
- }
- slc.Draw()
- output = output + fmt.Sprintf("\n%s", slc.View())
- }
- }
- return output
- }
- func (m Model) header() string { return titleStyle.Width(m.Width).Render("pingo v0") } // mark: opinionated render
- func (m Model) footer() string { // mark: opinionated render
- return footerStyle.Width(m.Width).Render("j/k: down/up\t|\tq/ctrl-c/esc: quit")
- }
- func (m Model) getVerticalMargin() int { return lipgloss.Height(m.header() + m.footer()) } // mark: opinionated render
- // Returns a batched set of tea.Cmd functions for each address.
- func (m Model) Poll() tea.Cmd {
- var cmds []tea.Cmd
- for i, element := range m.Addresses {
- cmds = append(cmds, func() tea.Msg {
- results, err := element.Poll()
- return pollResultMsg{results: results, err: err, index: i}
- })
- }
- return tea.Batch(cmds...)
- }
|