list.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. import "strings"
  6. // List displays []string as its items,
  7. // it has a Overflow option (default is "hidden"), when set to "hidden",
  8. // the item exceeding List's width is truncated, but when set to "wrap",
  9. // the overflowed text breaks into next line.
  10. /*
  11. strs := []string{
  12. "[0] notabug.org/themusicgod1/termui",
  13. "[1] editbox.go",
  14. "[2] interrupt.go",
  15. "[3] keyboard.go",
  16. "[4] output.go",
  17. "[5] random_out.go",
  18. "[6] dashboard.go",
  19. "[7] nsf/termbox-go"}
  20. ls := termui.NewList()
  21. ls.Items = strs
  22. ls.ItemFgColor = termui.ColorYellow
  23. ls.BorderLabel = "List"
  24. ls.Height = 7
  25. ls.Width = 25
  26. ls.Y = 0
  27. */
  28. type List struct {
  29. Block
  30. Items []string
  31. Overflow string
  32. ItemFgColor Attribute
  33. ItemBgColor Attribute
  34. }
  35. // NewList returns a new *List with current theme.
  36. func NewList() *List {
  37. l := &List{Block: *NewBlock()}
  38. l.Overflow = "hidden"
  39. l.ItemFgColor = ThemeAttr("list.item.fg")
  40. l.ItemBgColor = ThemeAttr("list.item.bg")
  41. return l
  42. }
  43. // Buffer implements Bufferer interface.
  44. func (l *List) Buffer() Buffer {
  45. buf := l.Block.Buffer()
  46. switch l.Overflow {
  47. case "wrap":
  48. cs := DefaultTxBuilder.Build(strings.Join(l.Items, "\n"), l.ItemFgColor, l.ItemBgColor)
  49. i, j, k := 0, 0, 0
  50. for i < l.innerArea.Dy() && k < len(cs) {
  51. w := cs[k].Width()
  52. if cs[k].Ch == '\n' || j+w > l.innerArea.Dx() {
  53. i++
  54. j = 0
  55. if cs[k].Ch == '\n' {
  56. k++
  57. }
  58. continue
  59. }
  60. buf.Set(l.innerArea.Min.X+j, l.innerArea.Min.Y+i, cs[k])
  61. k++
  62. j++
  63. }
  64. case "hidden":
  65. trimItems := l.Items
  66. if len(trimItems) > l.innerArea.Dy() {
  67. trimItems = trimItems[:l.innerArea.Dy()]
  68. }
  69. for i, v := range trimItems {
  70. cs := DTrimTxCls(DefaultTxBuilder.Build(v, l.ItemFgColor, l.ItemBgColor), l.innerArea.Dx())
  71. j := 0
  72. for _, vv := range cs {
  73. w := vv.Width()
  74. buf.Set(l.innerArea.Min.X+j, l.innerArea.Min.Y+i, vv)
  75. j += w
  76. }
  77. }
  78. }
  79. return buf
  80. }