feat(choose): improving selected option parse

This commit is contained in:
Vaniel 2022-09-06 16:02:32 -03:00 committed by Maas Lalani
parent 6abc94c87a
commit 76fc2f3d91
2 changed files with 3 additions and 14 deletions

View file

@ -48,15 +48,13 @@ func (o Options) Run() error {
// Keep track of the selected items.
currentSelected := 0
// Parse the selected items.
selectedItems := parseSelectedItems(o.Selected)
// Check if selected items should be used.
hasSelectedItems := o.Limit > 1 && len(selectedItems) > 0
hasSelectedItems := o.Limit > 1 && len(o.Selected) > 0
var items = make([]item, len(o.Options))
for i, option := range o.Options {
// Check if the option should be selected.
isSelected := hasSelectedItems && currentSelected < o.Limit && arrayContains(selectedItems, option)
isSelected := hasSelectedItems && currentSelected < o.Limit && arrayContains(o.Selected, option)
// If the option is selected then increment the current selected count.
if isSelected {
currentSelected++
@ -123,15 +121,6 @@ func (o Options) BeforeReset(ctx *kong.Context) error {
return nil
}
// Parse the options that should start selected.
func parseSelectedItems(selected string) []string {
selectedItems := strings.Split(strings.TrimSpace(selected), ",")
for i, selected := range selectedItems {
selectedItems[i] = strings.TrimSpace(selected)
}
return selectedItems
}
// Check if an array contains a value.
func arrayContains(strArray []string, value string) bool {
for _, str := range strArray {

View file

@ -13,7 +13,7 @@ type Options struct {
CursorPrefix string `help:"Prefix to show on the cursor item (hidden if limit is 1)" default:"[•] " env:"GUM_CHOOSE_CURSOR_PREFIX"`
SelectedPrefix string `help:"Prefix to show on selected items (hidden if limit is 1)" default:"[✕] " env:"GUM_CHOOSE_SELECTED_PREFIX"`
UnselectedPrefix string `help:"Prefix to show on unselected items (hidden if limit is 1)" default:"[ ] " env:"GUM_CHOOSE_UNSELECTED_PREFIX"`
Selected string `help:"Options that should start as selected" default:"" env:"GUM_CHOOSE_SELECTED"`
Selected []string `help:"Options that should start as selected" default:"" env:"GUM_CHOOSE_SELECTED"`
CursorStyle style.Styles `embed:"" prefix:"cursor." set:"defaultForeground=212" envprefix:"GUM_CHOOSE_CURSOR_"`
ItemStyle style.Styles `embed:"" prefix:"item." hidden:"" envprefix:"GUM_CHOOSE_ITEM_"`
SelectedItemStyle style.Styles `embed:"" prefix:"selected." set:"defaultForeground=212" envprefix:"GUM_CHOOSE_SELECTED_"`