AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.08k stars 351 forks source link

Support Custom formatting for Options in Select/ MultiSelect #253

Closed austince closed 4 years ago

austince commented 4 years ago

Hi there, this is awesome!

I've got a question/ an idea for a feature request and am wondering what you all think about it. For Select/MultiSelect questions, I often am trying to get a user to pick a complex data structure by some "name". Right now, I have to create a map of "name" => data to get the selected data after the prompt.

Is there any way to:
a) return the selected index instead of the selected value b) pass the slice of data into the options and have a custom formatter for the options shown to the user

If not, I'm thinking something similar to the Filter:

type dataType struct {
    id string
    name string
}

data := []dataType{
    {
        id: "1",
        name: "first",
    },
    {
        id: "2",
        name: "second",
    },
}
question := &survey.FormattedSelect{ // same as survey.Select but accepts an []interface{} for options and requires a Formatter
    Message: "Which VPC do you want to peer from?",
    Options: data,
    Formatter: func(item interface{}, index int) string {
        datum := item.(dataType)
        return datum.id + ":" + datum.name
    },
}
var selected dataType
_ = survey.AskOne(question, &selected)

I'm pretty new to go, so please let me know if this won't work hah, or if there is already a way to achieve this.

AlecAivazis commented 4 years ago

Hey @austince!

Thanks for the opening this issue and welcome to the Go community!

Unfortunately, this has been a long running issue that I ultimately had to close. We had difficulty figuring out how to design the API without interface{} being littered everywhere. In general, I try to avoid that since it makes it impossible for the user's code to guaruntee that types are properly assigned. We explored all sorts of options here if you want to take a look.

I know its not the answer you wanted, but I don't think this will be addressed any time soon. Your current approach of mapping names => data is a perfectly fine way to achieve what you want given the current API. Maybe when we release v3 we will add a way to do this, but I suspect the API will dramatically change in order to support it.

austince commented 4 years ago

Hey @AlecAivazis, no worries at all + thanks for the welcome! Sorry I didn't find those issues in my search before opening this one. That makes a lot of sense, and yeah I can create a utility around it instead. I really appreciate and admire the work that goes into designing this API -- looking forward to v3!