render.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package richtext
  2. import "strings"
  3. type RenderOptionsConsole struct {
  4. AnsiPalette AnsiPalette
  5. }
  6. func (opts RenderOptionsConsole) WrapSpanContent(content string, tags ([] string)) string {
  7. if opts.AnsiPalette != nil {
  8. var buf strings.Builder
  9. for _, tag := range tags {
  10. buf.WriteString(opts.AnsiPalette(tag))
  11. }
  12. buf.WriteString(content)
  13. buf.WriteString(reset)
  14. return buf.String()
  15. } else {
  16. return content
  17. }
  18. }
  19. type RenderOptionsHtml struct {
  20. // empty now
  21. }
  22. func (b Block) RenderPlainText() string {
  23. return b.RenderConsole(RenderOptionsConsole {})
  24. }
  25. func (b Block) RenderConsole(opts RenderOptionsConsole) string {
  26. var buf strings.Builder
  27. for _, l := range b.Lines {
  28. for i, span := range l.Spans {
  29. buf.WriteString(opts.WrapSpanContent(span.Content, span.Tags))
  30. if (i + 1) < len(l.Spans) {
  31. var next = l.Spans[(i + 1)]
  32. if !(strings.HasSuffix(span.Content, " ")) &&
  33. !(strings.HasPrefix(next.Content, " ")) &&
  34. next.Content != "," &&
  35. next.Content != ":" {
  36. buf.WriteRune(' ')
  37. }
  38. }
  39. }
  40. if len(l.Spans) > 0 {
  41. buf.WriteRune('\n')
  42. }
  43. }
  44. for _, child := range b.Children {
  45. buf.WriteString(child.RenderConsole(opts))
  46. }
  47. return buf.String()
  48. }
  49. func (b Block) RenderHtml(_ RenderOptionsHtml) Html {
  50. panic("not implemented") // TODO
  51. }