package door import ( "unicode" ) type Line struct { Text string DefaultColor string RenderF func(string) string UpdateF func() string } func (l *Line) Update() bool { if l.UpdateF == nil { return false } NewText := l.UpdateF() if NewText != l.Text { l.Text = NewText return true } return false } func (l *Line) Output() string { if l.RenderF == nil { return l.DefaultColor + l.Text } else { return l.RenderF(l.Text) } } // // The old example of a render function (before Render struct) // // Sample RenderF function // Upcase is BOLD Blue, everything else is Yellow /* func Render_BlueYellow(text string) string { var output string var lastColor string blue := ColorText("BOLD BLUE") yellow := ColorText("BOLD YELLOW") for _, letter := range text { if unicode.IsUpper(letter) { if lastColor != blue { lastColor = blue output += blue } output += string(letter) } else { if lastColor != yellow { lastColor = yellow output += yellow } output += string(letter) } } return output } */ type Render struct { Line string Result string Pos int LastColor string } func (r *Render) Append(color string, len int) { if color != r.LastColor { r.LastColor = color r.Result += color } if Unicode { // Treat unicode as []rune. r.Result += string([]rune(r.Line)[r.Pos : r.Pos+len]) } else { r.Result += r.Line[r.Pos : r.Pos+len] } r.Pos += len } // Sample RenderF function // Upcase is BOLD Blue, everything else is Yellow func RenderBlueYellow(text string) string { var r Render = Render{Line: text} blue := ColorText("BOLD BLUE") yellow := ColorText("BOLD YELLOW") for _, letter := range text { if unicode.IsUpper(letter) { r.Append(blue, 1) } else { r.Append(yellow, 1) } } return r.Result }