termui/widgets/list.go

98 lines
2.3 KiB
Go
Raw Normal View History

2019-01-24 12:12:10 +08:00
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
package widgets
import (
"image"
. "github.com/gizak/termui"
)
type List struct {
Block
2019-01-27 14:32:08 +08:00
Rows []string
WrapText bool
TextStyle Style
SelectedRow uint
topRow uint
SelectedRowStyle Style
2019-01-24 12:12:10 +08:00
}
func NewList() *List {
return &List{
2019-01-27 14:32:08 +08:00
Block: *NewBlock(),
TextStyle: Theme.List.Text,
SelectedRowStyle: Theme.List.Text,
2019-01-24 12:12:10 +08:00
}
}
func (self *List) Draw(buf *Buffer) {
self.Block.Draw(buf)
point := self.Inner.Min
if self.SelectedRow >= uint(self.Inner.Max.Y)+self.topRow-2 {
self.topRow = self.SelectedRow-uint(self.Inner.Max.Y)+2
} else if self.SelectedRow < self.topRow {
self.topRow = self.SelectedRow
}
2019-01-27 14:32:08 +08:00
for row := self.topRow; row < uint(len(self.Rows)) && point.Y < self.Inner.Max.Y; row++ {
2019-01-24 12:12:10 +08:00
cells := ParseText(self.Rows[row], self.TextStyle)
2019-01-27 14:32:08 +08:00
if self.WrapText {
2019-01-24 12:12:10 +08:00
cells = WrapCells(cells, uint(self.Inner.Dx()))
}
for j := 0; j < len(cells) && point.Y < self.Inner.Max.Y; j++ {
2019-01-27 14:32:08 +08:00
style := cells[j].Style
if row == self.SelectedRow {
style = self.SelectedRowStyle
}
2019-01-24 12:12:10 +08:00
if cells[j].Rune == '\n' {
point = image.Pt(self.Inner.Min.X, point.Y+1)
} else {
if point.X+1 == self.Inner.Max.X+1 && len(cells) > self.Inner.Dx() {
2019-01-27 14:32:08 +08:00
buf.SetCell(NewCell(ELLIPSES, style), point.Add(image.Pt(-1, 0)))
2019-01-24 12:12:10 +08:00
break
} else {
2019-01-27 14:32:08 +08:00
buf.SetCell(NewCell(cells[j].Rune, style), point)
2019-01-24 12:12:10 +08:00
point = point.Add(image.Pt(1, 0))
}
}
}
point = image.Pt(self.Inner.Min.X, point.Y+1)
}
2019-01-27 14:32:08 +08:00
if self.topRow > 0 {
buf.SetCell(
NewCell(UP_ARROW, NewStyle(ColorWhite)),
image.Pt(self.Inner.Max.X-1, self.Inner.Min.Y),
)
}
if len(self.Rows) > int(self.topRow)+self.Inner.Dy() {
buf.SetCell(
NewCell(DOWN_ARROW, NewStyle(ColorWhite)),
image.Pt(self.Inner.Max.X-1, self.Inner.Max.Y-1),
)
}
}
func (self *List) ScrollUp() {
if self.SelectedRow > 0 {
self.SelectedRow--
if self.SelectedRow < self.topRow {
self.topRow--
}
}
}
func (self *List) ScrollDown() {
if self.SelectedRow < uint(len(self.Rows))-1 {
self.SelectedRow++
if self.SelectedRow-self.topRow > uint(self.Inner.Dy()-1) {
self.topRow++
}
}
2019-01-24 12:12:10 +08:00
}