sampler-fork/component/textbox/textbox.go

72 lines
1.4 KiB
Go
Raw Permalink Normal View History

2019-04-10 02:30:21 +00:00
package textbox
import (
ui "github.com/gizak/termui/v3"
"github.com/sqshq/sampler/component"
"github.com/sqshq/sampler/config"
"github.com/sqshq/sampler/console"
"github.com/sqshq/sampler/data"
"image"
)
2019-07-27 04:15:35 +00:00
// TextBox represents a component with regular text
2019-04-10 02:30:21 +00:00
type TextBox struct {
*ui.Block
*data.Consumer
alert *data.Alert
text string
border bool
style ui.Style
2019-04-10 02:30:21 +00:00
}
func NewTextBox(c config.TextBoxConfig, palette console.Palette) *TextBox {
2019-06-21 04:32:15 +00:00
color := c.Color
if color == nil {
color = &palette.BaseColor
}
2019-04-10 02:30:21 +00:00
box := TextBox{
Block: component.NewBlock(c.Title, *c.Border, palette),
Consumer: data.NewConsumer(),
2019-06-21 04:32:15 +00:00
style: ui.NewStyle(*color),
2019-04-10 02:30:21 +00:00
}
go func() {
for {
select {
case sample := <-box.SampleChannel:
box.text = sample.Value
case alert := <-box.AlertChannel:
box.alert = alert
}
}
}()
return &box
}
func (t *TextBox) Draw(buffer *ui.Buffer) {
t.Block.Draw(buffer)
cells := ui.ParseStyles(t.text, ui.Theme.Paragraph.Text)
2019-04-20 02:07:44 +00:00
cells = ui.WrapCells(cells, uint(t.Inner.Dx()-2))
2019-04-10 02:30:21 +00:00
rows := ui.SplitCells(cells, '\n')
for y, row := range rows {
if y+t.Inner.Min.Y >= t.Inner.Max.Y-1 {
2019-04-10 02:30:21 +00:00
break
}
2019-04-20 02:07:44 +00:00
row = ui.TrimCells(row, t.Inner.Dx()-2)
2019-04-10 02:30:21 +00:00
for _, cx := range ui.BuildCellWithXArray(row) {
x, cell := cx.X, cx.Cell
cell.Style = t.style
2019-04-20 02:07:44 +00:00
buffer.SetCell(cell, image.Pt(x+1, y+1).Add(t.Inner.Min))
2019-04-10 02:30:21 +00:00
}
}
component.RenderAlert(t.alert, t.Rectangle, buffer)
}