renderer.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package core
  2. import (
  3. "strings"
  4. "github.com/kataras/survey/terminal"
  5. )
  6. type Renderer struct {
  7. lineCount int
  8. errorLineCount int
  9. }
  10. var ErrorTemplate = `{{color "red"}}{{ ErrorIcon }} Sorry, your reply was invalid: {{.Error}}{{color "reset"}}
  11. `
  12. func (r *Renderer) Error(invalid error) error {
  13. // since errors are printed on top we need to reset the prompt
  14. // as well as any previous error print
  15. r.resetPrompt(r.lineCount + r.errorLineCount)
  16. // we just cleared the prompt lines
  17. r.lineCount = 0
  18. out, err := RunTemplate(ErrorTemplate, invalid)
  19. if err != nil {
  20. return err
  21. }
  22. // keep track of how many lines are printed so we can clean up later
  23. r.errorLineCount = strings.Count(out, "\n")
  24. // send the message to the user
  25. terminal.Print(out)
  26. return nil
  27. }
  28. func (r *Renderer) resetPrompt(lines int) {
  29. // clean out current line in case tmpl didnt end in newline
  30. terminal.CursorHorizontalAbsolute(0)
  31. terminal.EraseLine(terminal.ERASE_LINE_ALL)
  32. // clean up what we left behind last time
  33. for i := 0; i < lines; i++ {
  34. terminal.CursorPreviousLine(1)
  35. terminal.EraseLine(terminal.ERASE_LINE_ALL)
  36. }
  37. }
  38. func (r *Renderer) Render(tmpl string, data interface{}) error {
  39. r.resetPrompt(r.lineCount)
  40. // render the template summarizing the current state
  41. out, err := RunTemplate(tmpl, data)
  42. if err != nil {
  43. return err
  44. }
  45. // keep track of how many lines are printed so we can clean up later
  46. r.lineCount = strings.Count(out, "\n")
  47. // print the summary
  48. terminal.Print(out)
  49. // nothing went wrong
  50. return nil
  51. }