line.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package door
  2. import (
  3. "unicode"
  4. )
  5. type Line struct {
  6. Text string
  7. DefaultColor string
  8. RenderF func(string) string
  9. UpdateF func() string
  10. }
  11. func (l *Line) Update() bool {
  12. if l.UpdateF == nil {
  13. return false
  14. }
  15. NewText := l.UpdateF()
  16. if NewText != l.Text {
  17. l.Text = NewText
  18. return true
  19. }
  20. return false
  21. }
  22. func (l *Line) Output() string {
  23. if l.RenderF == nil {
  24. return l.DefaultColor + l.Text
  25. } else {
  26. return l.RenderF(l.Text)
  27. }
  28. }
  29. //
  30. // The old example of a render function (before Render struct)
  31. //
  32. // Sample RenderF function
  33. // Upcase is BOLD Blue, everything else is Yellow
  34. /*
  35. func Render_BlueYellow(text string) string {
  36. var output string
  37. var lastColor string
  38. blue := ColorText("BOLD BLUE")
  39. yellow := ColorText("BOLD YELLOW")
  40. for _, letter := range text {
  41. if unicode.IsUpper(letter) {
  42. if lastColor != blue {
  43. lastColor = blue
  44. output += blue
  45. }
  46. output += string(letter)
  47. } else {
  48. if lastColor != yellow {
  49. lastColor = yellow
  50. output += yellow
  51. }
  52. output += string(letter)
  53. }
  54. }
  55. return output
  56. }
  57. */
  58. type Render struct {
  59. Line string
  60. Result string
  61. Pos int
  62. LastColor string
  63. }
  64. func (r *Render) Append(color string, len int) {
  65. if color != r.LastColor {
  66. r.LastColor = color
  67. r.Result += color
  68. }
  69. if Unicode {
  70. // Treat unicode as []rune.
  71. r.Result += string([]rune(r.Line)[r.Pos : r.Pos+len])
  72. } else {
  73. r.Result += r.Line[r.Pos : r.Pos+len]
  74. }
  75. r.Pos += len
  76. }
  77. // Sample RenderF function
  78. // Upcase is BOLD Blue, everything else is Yellow
  79. func RenderBlueYellow(text string) string {
  80. var r Render = Render{Line: text}
  81. blue := ColorText("BOLD BLUE")
  82. yellow := ColorText("BOLD YELLOW")
  83. for _, letter := range text {
  84. if unicode.IsUpper(letter) {
  85. r.Append(blue, 1)
  86. } else {
  87. r.Append(yellow, 1)
  88. }
  89. }
  90. return r.Result
  91. }