termui/paragraph.go

74 lines
1.6 KiB
Go
Raw Normal View History

2017-01-13 23:07:43 -07:00
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
2015-03-20 14:21:50 -06:00
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
2015-02-03 12:13:51 -07:00
package termui
2018-11-28 19:24:38 -07:00
// Paragraph displays a paragraph.
2015-03-24 15:16:43 -06:00
/*
2018-11-28 19:24:38 -07:00
par := termui.NewParagraph("Simple Text")
2015-03-24 15:16:43 -06:00
par.Height = 3
par.Width = 17
2016-10-14 05:48:50 -06:00
par.BorderLabel = "Label"
2015-03-24 15:16:43 -06:00
*/
2018-11-28 19:24:38 -07:00
type Paragraph struct {
2015-02-03 18:56:49 -07:00
Block
2015-10-08 20:11:26 -06:00
Text string
TextFgColor Attribute
TextBgColor Attribute
2016-03-10 13:49:31 -07:00
WrapLength int // words wrap limit. Note it may not work properly with multi-width char
2015-02-03 12:13:51 -07:00
}
2018-11-28 19:24:38 -07:00
// NewParagraph returns a new *Paragraph with given text as its content.
func NewParagraph(s string) *Paragraph {
return &Paragraph{
2015-10-08 20:11:26 -06:00
Block: *NewBlock(),
Text: s,
TextFgColor: ThemeAttr("par.text.fg"),
TextBgColor: ThemeAttr("par.text.bg"),
2015-10-29 20:55:30 -06:00
WrapLength: 0,
}
2015-02-03 12:13:51 -07:00
}
2015-03-24 15:16:43 -06:00
// Buffer implements Bufferer interface.
2018-11-28 19:24:38 -07:00
func (p *Paragraph) Buffer() Buffer {
2015-10-08 20:11:26 -06:00
buf := p.Block.Buffer()
2015-02-03 12:13:51 -07:00
fg, bg := p.TextFgColor, p.TextBgColor
2016-03-10 13:49:31 -07:00
cs := DefaultTxBuilder.Build(p.Text, fg, bg)
// wrap if WrapLength set
if p.WrapLength < 0 {
cs = wrapTx(cs, p.Width-2)
} else if p.WrapLength > 0 {
cs = wrapTx(cs, p.WrapLength)
2015-10-29 20:55:30 -06:00
}
y, x, n := 0, 0, 0
2015-10-08 20:11:26 -06:00
for y < p.innerArea.Dy() && n < len(cs) {
w := cs[n].Width()
if cs[n].Ch == '\n' || x+w > p.innerArea.Dx() {
y++
x = 0 // set x = 0
2015-10-08 20:11:26 -06:00
if cs[n].Ch == '\n' {
n++
2015-02-03 12:13:51 -07:00
}
2015-10-07 12:25:59 -06:00
if y >= p.innerArea.Dy() {
2015-10-08 20:11:26 -06:00
buf.Set(p.innerArea.Min.X+p.innerArea.Dx()-1,
2015-10-07 12:25:59 -06:00
p.innerArea.Min.Y+p.innerArea.Dy()-1,
2015-10-08 20:11:26 -06:00
Cell{Ch: '…', Fg: p.TextFgColor, Bg: p.TextBgColor})
break
}
2015-02-03 12:13:51 -07:00
continue
}
2015-10-08 20:11:26 -06:00
buf.Set(p.innerArea.Min.X+x, p.innerArea.Min.Y+y, cs[n])
n++
2015-10-08 20:11:26 -06:00
x += w
2015-02-03 12:13:51 -07:00
}
2015-10-08 20:11:26 -06:00
return buf
2015-02-03 12:13:51 -07:00
}