select.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package survey
  2. import (
  3. "errors"
  4. "strings"
  5. "gopkg.in/AlecAivazis/survey.v1/core"
  6. "gopkg.in/AlecAivazis/survey.v1/terminal"
  7. )
  8. /*
  9. Select is a prompt that presents a list of various options to the user
  10. for them to select using the arrow keys and enter. Response type is a string.
  11. color := ""
  12. prompt := &survey.Select{
  13. Message: "Choose a color:",
  14. Options: []string{"red", "blue", "green"},
  15. }
  16. survey.AskOne(prompt, &color, nil)
  17. */
  18. type Select struct {
  19. core.Renderer
  20. Message string
  21. Options []string
  22. Default string
  23. Help string
  24. PageSize int
  25. VimMode bool
  26. FilterMessage string
  27. filter string
  28. selectedIndex int
  29. useDefault bool
  30. showingHelp bool
  31. }
  32. // the data available to the templates when processing
  33. type SelectTemplateData struct {
  34. Select
  35. PageEntries []string
  36. SelectedIndex int
  37. Answer string
  38. ShowAnswer bool
  39. ShowHelp bool
  40. }
  41. var SelectQuestionTemplate = `
  42. {{- if .ShowHelp }}{{- color "cyan"}}{{ HelpIcon }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}}
  43. {{- color "green+hb"}}{{ QuestionIcon }} {{color "reset"}}
  44. {{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}}
  45. {{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}}
  46. {{- else}}
  47. {{- " "}}{{- color "cyan"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ HelpInputRune }} for more help{{end}}]{{color "reset"}}
  48. {{- "\n"}}
  49. {{- range $ix, $choice := .PageEntries}}
  50. {{- if eq $ix $.SelectedIndex}}{{color "cyan+b"}}{{ SelectFocusIcon }} {{else}}{{color "default+hb"}} {{end}}
  51. {{- $choice}}
  52. {{- color "reset"}}{{"\n"}}
  53. {{- end}}
  54. {{- end}}`
  55. // OnChange is called on every keypress.
  56. func (s *Select) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
  57. options := s.filterOptions()
  58. oldFilter := s.filter
  59. // if the user pressed the enter key
  60. if key == terminal.KeyEnter {
  61. if s.selectedIndex < len(options) {
  62. return []rune(options[s.selectedIndex]), 0, true
  63. }
  64. // if the user pressed the up arrow or 'k' to emulate vim
  65. } else if key == terminal.KeyArrowUp || (s.VimMode && key == 'k') {
  66. s.useDefault = false
  67. // if we are at the top of the list
  68. if s.selectedIndex == 0 {
  69. // start from the button
  70. s.selectedIndex = len(options) - 1
  71. } else {
  72. // otherwise we are not at the top of the list so decrement the selected index
  73. s.selectedIndex--
  74. }
  75. // if the user pressed down or 'j' to emulate vim
  76. } else if key == terminal.KeyArrowDown || (s.VimMode && key == 'j') {
  77. s.useDefault = false
  78. // if we are at the bottom of the list
  79. if s.selectedIndex == len(options)-1 {
  80. // start from the top
  81. s.selectedIndex = 0
  82. } else {
  83. // increment the selected index
  84. s.selectedIndex++
  85. }
  86. // only show the help message if we have one
  87. } else if key == core.HelpInputRune && s.Help != "" {
  88. s.showingHelp = true
  89. // if the user wants to toggle vim mode on/off
  90. } else if key == terminal.KeyEscape {
  91. s.VimMode = !s.VimMode
  92. // if the user hits any of the keys that clear the filter
  93. } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine {
  94. s.filter = ""
  95. // if the user is deleting a character in the filter
  96. } else if key == terminal.KeyDelete || key == terminal.KeyBackspace {
  97. // if there is content in the filter to delete
  98. if s.filter != "" {
  99. // subtract a line from the current filter
  100. s.filter = s.filter[0 : len(s.filter)-1]
  101. // we removed the last value in the filter
  102. }
  103. } else if key >= terminal.KeySpace {
  104. s.filter += string(key)
  105. // make sure vim mode is disabled
  106. s.VimMode = false
  107. // make sure that we use the current value in the filtered list
  108. s.useDefault = false
  109. }
  110. s.FilterMessage = ""
  111. if s.filter != "" {
  112. s.FilterMessage = " " + s.filter
  113. }
  114. if oldFilter != s.filter {
  115. // filter changed
  116. options = s.filterOptions()
  117. if len(options) > 0 && len(options) <= s.selectedIndex {
  118. s.selectedIndex = len(options) - 1
  119. }
  120. }
  121. // figure out the options and index to render
  122. // TODO if we have started filtering and were looking at the end of a list
  123. // and we have modified the filter then we should move the page back!
  124. opts, idx := paginate(s.PageSize, options, s.selectedIndex)
  125. // render the options
  126. s.Render(
  127. SelectQuestionTemplate,
  128. SelectTemplateData{
  129. Select: *s,
  130. SelectedIndex: idx,
  131. ShowHelp: s.showingHelp,
  132. PageEntries: opts,
  133. },
  134. )
  135. // if we are not pressing ent
  136. if len(options) <= s.selectedIndex {
  137. return []rune{}, 0, false
  138. }
  139. return []rune(options[s.selectedIndex]), 0, true
  140. }
  141. func (s *Select) filterOptions() []string {
  142. filter := strings.ToLower(s.filter)
  143. if filter == "" {
  144. return s.Options
  145. }
  146. answer := []string{}
  147. for _, o := range s.Options {
  148. if strings.Contains(strings.ToLower(o), filter) {
  149. answer = append(answer, o)
  150. }
  151. }
  152. return answer
  153. }
  154. func (s *Select) Prompt() (interface{}, error) {
  155. // if there are no options to render
  156. if len(s.Options) == 0 {
  157. // we failed
  158. return "", errors.New("please provide options to select from")
  159. }
  160. // start off with the first option selected
  161. sel := 0
  162. // if there is a default
  163. if s.Default != "" {
  164. // find the choice
  165. for i, opt := range s.Options {
  166. // if the option correponds to the default
  167. if opt == s.Default {
  168. // we found our initial value
  169. sel = i
  170. // stop looking
  171. break
  172. }
  173. }
  174. }
  175. // save the selected index
  176. s.selectedIndex = sel
  177. // figure out the options and index to render
  178. opts, idx := paginate(s.PageSize, s.Options, sel)
  179. // ask the question
  180. err := s.Render(
  181. SelectQuestionTemplate,
  182. SelectTemplateData{
  183. Select: *s,
  184. PageEntries: opts,
  185. SelectedIndex: idx,
  186. },
  187. )
  188. if err != nil {
  189. return "", err
  190. }
  191. // by default, use the default value
  192. s.useDefault = true
  193. rr := s.NewRuneReader()
  194. rr.SetTermMode()
  195. defer rr.RestoreTermMode()
  196. cursor := s.NewCursor()
  197. cursor.Hide() // hide the cursor
  198. defer cursor.Show() // show the cursor when we're done
  199. // start waiting for input
  200. for {
  201. r, _, err := rr.ReadRune()
  202. if err != nil {
  203. return "", err
  204. }
  205. if r == '\r' || r == '\n' {
  206. break
  207. }
  208. if r == terminal.KeyInterrupt {
  209. return "", terminal.InterruptErr
  210. }
  211. if r == terminal.KeyEndTransmission {
  212. break
  213. }
  214. s.OnChange(nil, 0, r)
  215. }
  216. options := s.filterOptions()
  217. s.filter = ""
  218. s.FilterMessage = ""
  219. var val string
  220. // if we are supposed to use the default value
  221. if s.useDefault || s.selectedIndex >= len(options) {
  222. // if there is a default value
  223. if s.Default != "" {
  224. // use the default value
  225. val = s.Default
  226. } else if len(options) > 0 {
  227. // there is no default value so use the first
  228. val = options[0]
  229. }
  230. // otherwise the selected index points to the value
  231. } else if s.selectedIndex < len(options) {
  232. // the
  233. val = options[s.selectedIndex]
  234. }
  235. return val, err
  236. }
  237. func (s *Select) Cleanup(val interface{}) error {
  238. return s.Render(
  239. SelectQuestionTemplate,
  240. SelectTemplateData{
  241. Select: *s,
  242. Answer: val.(string),
  243. ShowAnswer: true,
  244. },
  245. )
  246. }