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