termui/list.go

90 lines
2.0 KiB
Go
Raw Normal View History

2017-01-14 14:07:43 +08:00
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
2015-03-21 04:21:50 +08:00
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
2015-02-04 09:56:49 +08:00
package termui
2015-10-09 10:11:26 +08:00
import "strings"
2015-03-25 05:16:43 +08: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
2016-10-14 19:48:50 +08:00
ls.BorderLabel = "List"
2015-03-25 05:16:43 +08:00
ls.Height = 7
ls.Width = 25
ls.Y = 0
*/
2015-02-04 09:56:49 +08:00
type List struct {
Block
2015-10-09 10:11:26 +08:00
Items []string
Overflow string
ItemFgColor Attribute
ItemBgColor Attribute
2015-02-04 09:56:49 +08:00
}
2015-03-25 05:16:43 +08:00
// NewList returns a new *List with current theme.
2015-02-04 09:56:49 +08:00
func NewList() *List {
l := &List{Block: *NewBlock()}
l.Overflow = "hidden"
2015-10-09 10:11:26 +08:00
l.ItemFgColor = ThemeAttr("list.item.fg")
l.ItemBgColor = ThemeAttr("list.item.bg")
2015-02-04 09:56:49 +08:00
return l
}
2015-03-25 05:16:43 +08:00
// Buffer implements Bufferer interface.
2015-10-09 10:11:26 +08:00
func (l *List) Buffer() Buffer {
buf := l.Block.Buffer()
2015-10-09 10:11:26 +08: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-06 03:55:29 +08:00
}
2015-10-09 10:11:26 +08:00
continue
2015-04-06 03:55:29 +08:00
}
2015-10-09 10:11:26 +08:00
buf.Set(l.innerArea.Min.X+j, l.innerArea.Min.Y+i, cs[k])
k++
j++
2015-02-04 09:56:49 +08:00
}
2015-10-09 10:11:26 +08: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 09:56:49 +08:00
}
}
2015-10-09 10:11:26 +08:00
return buf
2015-02-04 09:56:49 +08:00
}