command.go
This file
Path
choose/command.go
174 lines · 4.5 KiB · Go
Last changed by
chore: prepare v2 (#1116)Drew Smirnoffbefore adoption02d6f06
History of this fileTake it
1package choose23import (4 "errors"5 "fmt"6 "os"7 "slices"8 "sort"9 "strings"1011 "charm.land/bubbles/v2/help"12 "charm.land/bubbles/v2/paginator"13 tea "charm.land/bubbletea/v2"14 "charm.land/gum/v2/internal/stdin"15 "charm.land/gum/v2/internal/timeout"16 "charm.land/gum/v2/internal/tty"17 "charm.land/gum/v2/style"18)1920// Run provides a shell script interface for choosing between different through21// options.22func (o Options) Run() error {23 input, _ := stdin.Read(stdin.StripANSI(o.StripANSI))24 if len(o.Options) > 0 && len(o.Selected) == 0 {25 o.Selected = strings.Split(input, o.InputDelimiter)26 } else if len(o.Options) == 0 {27 if input == "" {28 return errors.New("no options provided, see `gum choose --help`")29 }30 o.Options = strings.Split(input, o.InputDelimiter)31 }3233 // normalize options into a map34 options := map[string]string{}35 // keep the labels in the user-provided order36 var labels []string37 for _, opt := range o.Options {38 if o.LabelDelimiter == "" {39 options[opt] = opt40 continue41 }42 label, value, ok := strings.Cut(opt, o.LabelDelimiter)43 if !ok {44 return fmt.Errorf("invalid option format: %q", opt)45 }46 labels = append(labels, label)47 options[label] = value48 }49 if o.LabelDelimiter != "" {50 o.Options = labels51 }5253 if o.SelectIfOne && len(o.Options) == 1 {54 fmt.Println(options[o.Options[0]])55 return nil56 }5758 // We don't need to display prefixes if we are only picking one option.59 // Simply displaying the cursor is enough.60 if o.Limit == 1 && !o.NoLimit {61 o.SelectedPrefix = ""62 o.UnselectedPrefix = ""63 o.CursorPrefix = ""64 }6566 if o.NoLimit {67 o.Limit = len(o.Options) + 168 }6970 if o.Ordered {71 slices.SortFunc(o.Options, strings.Compare)72 }7374 isSelectAll := len(o.Selected) == 1 && o.Selected[0] == "*"7576 // Keep track of the selected items.77 currentSelected := 078 // Check if selected items should be used.79 hasSelectedItems := len(o.Selected) > 080 startingIndex := 081 currentOrder := 082 items := make([]item, len(o.Options))83 for i, option := range o.Options {84 var order int85 // Check if the option should be selected.86 isSelected := hasSelectedItems && currentSelected < o.Limit && (isSelectAll || slices.Contains(o.Selected, option))87 // If the option is selected then increment the current selected count.88 if isSelected {89 if o.Limit == 1 {90 // When the user can choose only one option don't select the option but91 // start with the cursor hovering over it.92 startingIndex = i93 isSelected = false94 } else {95 currentSelected++96 order = currentOrder97 currentOrder++98 }99 }100 items[i] = item{text: option, selected: isSelected, order: order}101 }102103 // Use the pagination model to display the current and total number of104 // pages.105 top, right, bottom, left := style.ParsePadding(o.Padding)106 pager := paginator.New()107 pager.SetTotalPages((len(items) + o.Height - 1) / o.Height)108 pager.PerPage = o.Height109 pager.Type = paginator.Dots110 pager.KeyMap = paginator.KeyMap{}111 pager.Page = startingIndex / o.Height112113 km := defaultKeymap()114 if o.NoLimit || o.Limit > 1 {115 km.Toggle.SetEnabled(true)116 }117 if o.NoLimit {118 km.ToggleAll.SetEnabled(true)119 }120121 m := model{122 index: startingIndex,123 currentOrder: currentOrder,124 height: o.Height,125 padding: []int{top, right, bottom, left},126 cursor: o.Cursor,127 header: o.Header,128 selectedPrefix: o.SelectedPrefix,129 unselectedPrefix: o.UnselectedPrefix,130 cursorPrefix: o.CursorPrefix,131 items: items,132 limit: o.Limit,133 paginator: pager,134 cursorStyle: o.CursorStyle.ToLipgloss(),135 headerStyle: o.HeaderStyle.ToLipgloss(),136 itemStyle: o.ItemStyle.ToLipgloss(),137 selectedItemStyle: o.SelectedItemStyle.ToLipgloss(),138 numSelected: currentSelected,139 showHelp: o.ShowHelp,140 help: help.New(),141 keymap: km,142 }143144 ctx, cancel := timeout.Context(o.Timeout)145 defer cancel()146147 // Disable Keybindings since we will control it ourselves.148 tm, err := tea.NewProgram(149 m,150 tea.WithOutput(os.Stderr),151 tea.WithContext(ctx),152 ).Run()153 if err != nil {154 return fmt.Errorf("unable to pick selection: %w", err)155 }156 m = tm.(model)157 if !m.submitted {158 return errors.New("nothing selected")159 }160 if o.Ordered && o.Limit > 1 {161 sort.Slice(m.items, func(i, j int) bool {162 return m.items[i].order < m.items[j].order163 })164 }165166 var out []string167 for _, item := range m.items {168 if item.selected {169 out = append(out, options[item.text])170 }171 }172 tty.Println(strings.Join(out, o.OutputDelimiter))173 return nil174}