termui/list.go

90 lines
2.0 KiB
Go
Raw Normal View History

2015-03-20 20:21:50 +00:00
// Copyright 2015 Zack Guo <gizak@icloud.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
2015-02-04 01:56:49 +00:00
package termui
2015-10-09 02:11:26 +00:00
import "strings"
2015-03-24 21:16:43 +00:00
// List displays []string as its items,
// it has a Overflow option (default is "hidden"), when set to "hidden",
// the item exceeding List's width is truncated, but when set to "wrap",
// the overflowed text breaks into next line.
/*
strs := []string{
"[0] github.com/gizak/termui",
"[1] editbox.go",
"[2] iterrupt.go",
"[3] keyboard.go",
"[4] output.go",
"[5] random_out.go",
"[6] dashboard.go",
"[7] nsf/termbox-go"}
ls := termui.NewList()
ls.Items = strs
ls.ItemFgColor = termui.ColorYellow
ls.Border.Label = "List"
ls.Height = 7
ls.Width = 25
ls.Y = 0
*/
2015-02-04 01:56:49 +00:00
type List struct {
Block
2015-10-09 02:11:26 +00:00
Items []string
Overflow string
ItemFgColor Attribute
ItemBgColor Attribute
2015-02-04 01:56:49 +00:00
}
2015-03-24 21:16:43 +00:00
// NewList returns a new *List with current theme.
2015-02-04 01:56:49 +00:00
func NewList() *List {
l := &List{Block: *NewBlock()}
l.Overflow = "hidden"
2015-10-09 02:11:26 +00:00
l.ItemFgColor = ThemeAttr("list.item.fg")
l.ItemBgColor = ThemeAttr("list.item.bg")
2015-02-04 01:56:49 +00:00
return l
}
2015-03-24 21:16:43 +00:00
// Buffer implements Bufferer interface.
2015-10-09 02:11:26 +00:00
func (l *List) Buffer() Buffer {
buf := l.Block.Buffer()
2015-10-09 02:11:26 +00:00
switch l.Overflow {
case "wrap":
cs := DefaultTxBuilder.Build(strings.Join(l.Items, "\n"), l.ItemFgColor, l.ItemBgColor)
i, j, k := 0, 0, 0
for i < l.innerArea.Dy() && k < len(cs) {
w := cs[k].Width()
if cs[k].Ch == '\n' || j+w > l.innerArea.Dx() {
i++
j = 0
if cs[k].Ch == '\n' {
k++
2015-04-05 19:55:29 +00:00
}
2015-10-09 02:11:26 +00:00
continue
2015-04-05 19:55:29 +00:00
}
2015-10-09 02:11:26 +00:00
buf.Set(l.innerArea.Min.X+j, l.innerArea.Min.Y+i, cs[k])
k++
j++
2015-02-04 01:56:49 +00:00
}
2015-10-09 02:11:26 +00:00
case "hidden":
trimItems := l.Items
if len(trimItems) > l.innerArea.Dy() {
trimItems = trimItems[:l.innerArea.Dy()]
}
for i, v := range trimItems {
cs := DTrimTxCls(DefaultTxBuilder.Build(v, l.ItemFgColor, l.ItemBgColor), l.innerArea.Dx())
j := 0
for _, vv := range cs {
w := vv.Width()
buf.Set(l.innerArea.Min.X+j, l.innerArea.Min.Y+i, vv)
j += w
}
2015-02-04 01:56:49 +00:00
}
}
2015-10-09 02:11:26 +00:00
return buf
2015-02-04 01:56:49 +00:00
}