Implemented TextRenderers to List.

This commit is contained in:
Matteo Kloiber 2015-04-05 21:55:29 +02:00
parent be167436b7
commit 6c168b2d04

71
list.go
View File

@ -4,8 +4,6 @@
package termui package termui
import "strings"
// List displays []string as its items, // List displays []string as its items,
// it has a Overflow option (default is "hidden"), when set to "hidden", // 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 item exceeding List's width is truncated, but when set to "wrap",
@ -31,10 +29,11 @@ import "strings"
*/ */
type List struct { type List struct {
Block Block
Items []string Items []string
Overflow string Overflow string
ItemFgColor Attribute ItemFgColor Attribute
ItemBgColor Attribute ItemBgColor Attribute
RendererFactory TextRendererFactory
} }
// NewList returns a new *List with current theme. // NewList returns a new *List with current theme.
@ -43,6 +42,7 @@ func NewList() *List {
l.Overflow = "hidden" l.Overflow = "hidden"
l.ItemFgColor = theme.ListItemFg l.ItemFgColor = theme.ListItemFg
l.ItemBgColor = theme.ListItemBg l.ItemBgColor = theme.ListItemBg
l.RendererFactory = NoopRendererFactory{}
return l return l
} }
@ -51,29 +51,24 @@ func (l *List) Buffer() []Point {
ps := l.Block.Buffer() ps := l.Block.Buffer()
switch l.Overflow { switch l.Overflow {
case "wrap": case "wrap":
rs := str2runes(strings.Join(l.Items, "\n")) y := 0
i, j, k := 0, 0, 0 for _, item := range l.Items {
for i < l.innerHeight && k < len(rs) { x := 0
w := charWidth(rs[k])
if rs[k] == '\n' || j+w > l.innerWidth { renderer := l.RendererFactory.TextRenderer(item)
i++ sequence := renderer.Render(l.ItemFgColor, l.ItemBgColor)
j = 0 for n := range []rune(sequence.NormalizedText) {
if rs[k] == '\n' { point, width := sequence.PointAt(n, x+l.innerX, y+l.innerY)
k++
if width+x <= l.innerWidth {
ps = append(ps, point)
x += width
} else {
y++
x = 0
} }
continue
} }
pi := Point{} y++
pi.X = l.innerX + j
pi.Y = l.innerY + i
pi.Ch = rs[k]
pi.Bg = l.ItemBgColor
pi.Fg = l.ItemFgColor
ps = append(ps, pi)
k++
j++
} }
case "hidden": case "hidden":
@ -81,23 +76,15 @@ func (l *List) Buffer() []Point {
if len(trimItems) > l.innerHeight { if len(trimItems) > l.innerHeight {
trimItems = trimItems[:l.innerHeight] trimItems = trimItems[:l.innerHeight]
} }
for i, v := range trimItems {
rs := trimStr2Runes(v, l.innerWidth)
j := 0
for _, vv := range rs { for y, item := range trimItems {
w := charWidth(vv) text := TrimStrIfAppropriate(item, l.innerWidth)
p := Point{} render := l.RendererFactory.TextRenderer(text)
p.X = l.innerX + j sequence := render.RenderSequence(0, -1, l.ItemFgColor, l.ItemBgColor)
p.Y = l.innerY + i t, _ := sequence.Buffer(l.innerX, y+l.innerY)
p.Ch = vv ps = append(ps, t...)
p.Bg = l.ItemBgColor
p.Fg = l.ItemFgColor
ps = append(ps, p)
j += w
}
} }
} }
return l.Block.chopOverflow(ps) return l.Block.chopOverflow(ps)
} }