line.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // Sample RenderF function
  30. // Upcase is BOLD Blue, everything else is Yellow
  31. func RenderBlueYellow(text string) string {
  32. var output string
  33. var lastColor string
  34. blue := ColorText("BOLD BLUE")
  35. yellow := ColorText("BOLD YELLOW")
  36. for _, letter := range text {
  37. if unicode.IsUpper(letter) {
  38. if lastColor != blue {
  39. lastColor = blue
  40. output += blue
  41. }
  42. output += string(letter)
  43. } else {
  44. if lastColor != yellow {
  45. lastColor = yellow
  46. output += yellow
  47. }
  48. output += string(letter)
  49. }
  50. }
  51. return output
  52. }
  53. type Render struct {
  54. Line string
  55. Result string
  56. Pos int
  57. LastColor string
  58. }
  59. func (r *Render) Append(color string, len int) {
  60. if color != r.LastColor {
  61. r.LastColor = color
  62. r.Result += color
  63. }
  64. r.Result += r.Line[r.Pos : r.Pos+len]
  65. r.Pos += len
  66. }