huh icon indicating copy to clipboard operation
huh copied to clipboard

How can I dynamically generate options in a list?

Open iloveicedgreentea opened this issue 10 months ago • 3 comments

I have code like this

huh.NewGroup(
	huh.NewSelect[string]().
		Key(keyAppNames).
		// add the app names here
		Options(huh.NewOptions(m.appState.AppNames...)...).
		Title("Applications for "+m.appState.UserName).
		Description("Select your app. You may scroll or filter"),
),

m.appState.AppNames is fetched from some API. If I fetch it async after the form is completed, I have to remake the form to get it to show up. Calling form.Update() does not seem to refresh it. What is the correct way to update values in a form after the form is created?

In other words, lets say I have 4 groups. The first 3 ask the user for inputs. The fourth's list is based on the API response which depends on the items in the first 3 groups. Right now, I would have to remake the form and then call NextGroup to get to the page I was on, or make a second form and switch to that, but then I lose shift+tab functionality.

What I would like to happen is this:

  1. Form is generated
  2. Update() function receives some tea.Msg
  3. form.Update() remakes the fields because the underlying variable changed (m.appState.AppNames)
  4. the form is updated

Some alternatives I considered

  1. making the form again and using NextGroup to "scroll" back to the right place. Kind of hacky and loses the form variables that I will have to save externally and also requires me to keep track of positions. Having the page field external would be nice so I can specify which group to switch to

  2. Making a second form and switching model.form to it. This is simpler but loses the shift-tab functionality

iloveicedgreentea avatar Apr 09 '24 19:04 iloveicedgreentea

I did your option 2... I have a lot of dynamic steps. I wish there was a JIT factory approach. Seems similar to #69.

WTIGER001 avatar Apr 10 '24 15:04 WTIGER001

For now I ended up refactoring to go back with a single form and a helper function to scroll like this

func (m *Model) scrollGroupUp(scrollAmount int) {
	for i := 0; i < scrollAmount; i++ {
		m.form.NextGroup()
	}
}

It would be nice to have direct access to the selected group, as well as exporting much more fields from the Form struct

iloveicedgreentea avatar Apr 10 '24 17:04 iloveicedgreentea

Hi! We're planning on supporting this is an official capacity. Please follow https://github.com/charmbracelet/huh/issues/69 for updates and discussion.

meowgorithm avatar Apr 10 '24 18:04 meowgorithm

Hi, closing this in favour of #69

maaslalani avatar May 25 '24 17:05 maaslalani