manifoldco/promptui

How do I use Select with an struct template that allows to add items?

muuvmuuv opened this issue · 2 comments

I would like to use a custom struct template but also let the user choose a custom input. In my case I want the user to select a new version and if he wants to add major-beta-anything-else he can input a string which is validated by semver. From what I see this is currently not possible?

Here is my code:

	incList := []inc{
		{Name: "Patch", Version: patchV.String()},
		{Name: "Minor", Version: minorV.String()},
		{Name: "Major", Version: majorV.String()},
	}

	templates := &promptui.SelectTemplates{
		Label:    "{{ . }}",
		Active:   "❯ {{ .Name | cyan }} ({{ .Version }})",
		Selected: "{{ . }}",
		Inactive: "  {{ .Name | cyan }} ({{ .Version }})",
		Details: `--------- Selected ----------
{{ "Name:" | faint }}	{{ .Name }}
{{ "Version:" | faint }}	{{ .Version }}`,
	}

	prompt := promptui.Select{
		Label:        "Select new version",
		Items:        incList,
		Templates:    templates,
		HideSelected: true,
		Size:         10,
	}

Maybe SelectWithAdd can be extended by:

	prompt := promptui.SelectWithAdd{
		Label:        "Select new version",
		Items:        incList,
		Templates:    templates,
		HideSelected: true,
		Size:         10,
                AddLabel: "Others",
                AddTransform: func(input string) {
 return inc{ Name: "other", Version: input }
}
	}

Found a workaround/good solution:

	incList := []inc{
		{Name: "Patch", Version: patchV.String()},
		{Name: "Minor", Version: minorV.String()},
		{Name: "Major", Version: majorV.String()},
		{Name: "Other", Version: ""},
	}

         /// .....

	if result.Version == "" {
		prompt := promptui.Prompt{
			Label:       "Number",
			HideEntered: true,
			Validate: func(input string) error {
				_, err := semver.NewVersion(input)
				if err != nil {
					return errors.New("This is not a valid version")
				}
				return nil
			},
		}
		oResult, err := prompt.Run()
		if err != nil {
			log.Fatal(fmt.Errorf("Prompt failed %v", err))
		}
		result.Version = oResult
	}

@muuvmuuv Thanks, that is helpful.