par.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved.
  2. // Use of this source code is governed by a MIT license that can
  3. // be found in the LICENSE file.
  4. package termui
  5. // Par displays a paragraph.
  6. /*
  7. par := termui.NewPar("Simple Text")
  8. par.Height = 3
  9. par.Width = 17
  10. par.BorderLabel = "Label"
  11. */
  12. type Par struct {
  13. Block
  14. Text string
  15. TextFgColor Attribute
  16. TextBgColor Attribute
  17. WrapLength int // words wrap limit. Note it may not work properly with multi-width char
  18. }
  19. // NewPar returns a new *Par with given text as its content.
  20. func NewPar(s string) *Par {
  21. return &Par{
  22. Block: *NewBlock(),
  23. Text: s,
  24. TextFgColor: ThemeAttr("par.text.fg"),
  25. TextBgColor: ThemeAttr("par.text.bg"),
  26. WrapLength: 0,
  27. }
  28. }
  29. // Buffer implements Bufferer interface.
  30. func (p *Par) Buffer() Buffer {
  31. buf := p.Block.Buffer()
  32. fg, bg := p.TextFgColor, p.TextBgColor
  33. cs := DefaultTxBuilder.Build(p.Text, fg, bg)
  34. // wrap if WrapLength set
  35. if p.WrapLength < 0 {
  36. cs = wrapTx(cs, p.Width-2)
  37. } else if p.WrapLength > 0 {
  38. cs = wrapTx(cs, p.WrapLength)
  39. }
  40. y, x, n := 0, 0, 0
  41. for y < p.innerArea.Dy() && n < len(cs) {
  42. w := cs[n].Width()
  43. if cs[n].Ch == '\n' || x+w > p.innerArea.Dx() {
  44. y++
  45. x = 0 // set x = 0
  46. if cs[n].Ch == '\n' {
  47. n++
  48. }
  49. if y >= p.innerArea.Dy() {
  50. buf.Set(p.innerArea.Min.X+p.innerArea.Dx()-1,
  51. p.innerArea.Min.Y+p.innerArea.Dy()-1,
  52. Cell{Ch: '…', Fg: p.TextFgColor, Bg: p.TextBgColor})
  53. break
  54. }
  55. continue
  56. }
  57. buf.Set(p.innerArea.Min.X+x, p.innerArea.Min.Y+y, cs[n])
  58. n++
  59. x += w
  60. }
  61. return buf
  62. }