package ui import ( "fmt" "strings" "github.com/charmbracelet/bubbles/cursor" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "ghosttyconf/internal/schema" ) // result is what an editor produces when it closes. type result struct { cancel bool // values are the new raw values. nil (without cancel) removes the // option from the config file, restoring the default. values []string } func cancelled() *result { return &result{cancel: true} } func valuesResult(v ...string) *result { return &result{values: v} } // editor edits the value of one option (or one entry of a list option). type editor interface { Update(msg tea.Msg) (tea.Cmd, *result) View(width, height int) string Help() string } func newInput(value, placeholder string) textinput.Model { ti := textinput.New() ti.Prompt = "› " ti.PromptStyle = stAccent ti.Placeholder = placeholder ti.PlaceholderStyle = stDim ti.Cursor.SetMode(cursor.CursorStatic) ti.SetValue(value) ti.CursorEnd() ti.Focus() return ti } // scrollWindow returns the first visible row so that cursor stays visible. func scrollWindow(cursor, top, height, n int) int { if height <= 0 { return 0 } if cursor < top { top = cursor } if cursor >= top+height { top = cursor - height + 1 } if top > n-height { top = max(0, n-height) } return max(0, top) } // moveCursor applies common list navigation keys. func moveCursor(key string, cursor, n, page int) (int, bool) { if n == 0 { return 0, false } switch key { case "up", "k", "ctrl+p": cursor-- case "down", "j", "ctrl+n": cursor++ case "pgup": cursor -= page case "pgdown": cursor += page case "home", "g": cursor = 0 case "end", "G": cursor = n - 1 default: return cursor, false } return min(max(cursor, 0), n-1), true } // --------------------------------------------------------------------------- // Choice editor: booleans, enums and enums with a custom value. type choiceItem struct { value string label string custom bool } type choiceEditor struct { opt *schema.Option items []choiceItem cursor int top int height int current string text *textEditor // active while typing a custom value } func newChoiceEditor(o *schema.Option, current string) *choiceEditor { e := &choiceEditor{opt: o, current: schema.Unquote(current)} values := o.Values if o.Kind == schema.KindBool { values = []string{"true", "false"} } for _, v := range values { e.items = append(e.items, choiceItem{value: v, label: v}) } if o.Kind == schema.KindChoice { label := "Custom value…" if e.current != "" && !contains(values, e.current) { label = "Custom value: " + e.current } e.items = append(e.items, choiceItem{label: label, custom: true}) } e.cursor = 0 effective := e.current if effective == "" { effective = o.Default() } for i, it := range e.items { if it.value == effective || (it.custom && effective != "" && !contains(values, effective)) { e.cursor = i break } } return e } func (e *choiceEditor) Update(msg tea.Msg) (tea.Cmd, *result) { if e.text != nil { cmd, res := e.text.Update(msg) if res != nil { e.text = nil if res.cancel { return nil, nil } return nil, res } return cmd, nil } km, ok := msg.(tea.KeyMsg) if !ok { return nil, nil } key := km.String() if c, moved := moveCursor(key, e.cursor, len(e.items), max(1, e.height-1)); moved { e.cursor = c return nil, nil } switch key { case "esc", "q": return nil, cancelled() case "enter", " ": it := e.items[e.cursor] if it.custom { v := "" if !contains(e.opt.Values, e.current) { v = e.current } e.text = newTextEditor(e.opt, v) return nil, nil } return nil, valuesResult(it.value) } return nil, nil } func (e *choiceEditor) View(width, height int) string { if e.text != nil { return e.text.View(width, height) } e.height = height e.top = scrollWindow(e.cursor, e.top, height, len(e.items)) var lines []string def := e.opt.Default() for i := e.top; i < len(e.items) && len(lines) < height; i++ { it := e.items[i] sel := i == e.cursor labelSt := lipgloss.NewStyle() if sel { labelSt = stBold } segs := []seg{cursorSeg(sel), styled(fit(it.label, 28), labelSt), plain(" ")} if !it.custom && it.value == e.current { segs = append(segs, styled("● current ", stSet)) } if !it.custom && it.value == def { segs = append(segs, styled("default", stDim)) } lines = append(lines, renderRow(segs, width, sel)) } return strings.Join(lines, "\n") } func (e *choiceEditor) Help() string { if e.text != nil { return e.text.Help() } return "↑↓ choose · enter select · esc cancel" } // --------------------------------------------------------------------------- // Flags editor: packed structs such as shell-integration-features. type flagsEditor struct { opt *schema.Option state map[string]bool def map[string]bool cursor int } func newFlagsEditor(o *schema.Option, current string) *flagsEditor { return &flagsEditor{opt: o, state: o.ParseFlags(current), def: o.ParseFlags("")} } func (e *flagsEditor) Update(msg tea.Msg) (tea.Cmd, *result) { km, ok := msg.(tea.KeyMsg) if !ok { return nil, nil } key := km.String() if c, moved := moveCursor(key, e.cursor, len(e.opt.Flags), 5); moved { e.cursor = c return nil, nil } switch key { case "esc", "q": return nil, cancelled() case " ", "x": f := e.opt.Flags[e.cursor] e.state[f] = !e.state[f] case "a": for _, f := range e.opt.Flags { e.state[f] = true } case "n": for _, f := range e.opt.Flags { e.state[f] = false } case "d": for _, f := range e.opt.Flags { e.state[f] = e.def[f] } case "enter": return nil, valuesResult(e.opt.FormatFlags(e.state)) } return nil, nil } func (e *flagsEditor) View(width, height int) string { var lines []string for i, f := range e.opt.Flags { box := styled("[ ]", stDim) if e.state[f] { box = styled("[✓]", stSet) } segs := []seg{cursorSeg(i == e.cursor), box, plain(" " + fit(f, 22) + " ")} if e.state[f] != e.def[f] { segs = append(segs, styled("changed from default", stChanged)) } lines = append(lines, renderRow(segs, width, i == e.cursor)) } lines = append(lines, "", stDim.Render("Result: ")+stCode.Render(e.opt.FormatFlags(e.state))) return strings.Join(lines, "\n") } func (e *flagsEditor) Help() string { return "↑↓ move · space toggle · a all · n none · d defaults · enter apply · esc cancel" } // --------------------------------------------------------------------------- // Text editor with validation, used for numbers, colors, durations, paths // and free text. type textEditor struct { opt *schema.Option input textinput.Model err string // item is set when editing one entry of a list option: an empty value // then means "remove this entry" rather than "reset to default". item bool } func newTextEditor(o *schema.Option, value string) *textEditor { placeholder := o.Default() if placeholder == "" { placeholder = o.Hint } return &textEditor{opt: o, input: newInput(value, placeholder)} } func (e *textEditor) Update(msg tea.Msg) (tea.Cmd, *result) { if km, ok := msg.(tea.KeyMsg); ok { switch km.String() { case "esc": return nil, cancelled() case "enter": v := strings.TrimSpace(e.input.Value()) if v == "" { return nil, &result{} } if err := e.opt.Validate(v); err != nil { e.err = err.Error() return nil, nil } return nil, valuesResult(v) case "up", "down": if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric { delta := 1 if km.String() == "down" { delta = -1 } if v, ok := stepValue(e.opt, e.input.Value(), delta); ok { e.input.SetValue(v) e.input.CursorEnd() } return nil, nil } } } var cmd tea.Cmd e.input, cmd = e.input.Update(msg) e.err = "" return cmd, nil } func (e *textEditor) View(width, height int) string { e.input.Width = max(10, width-4) var lines []string lines = append(lines, e.input.View(), "") v := strings.TrimSpace(e.input.Value()) switch { case e.err != "": lines = append(lines, stError.Render("✗ "+e.err)) case v == "" && e.item: lines = append(lines, stDim.Render("Empty: the entry will be removed.")) case v == "": lines = append(lines, stDim.Render("Empty: the option will be reset to its default.")) default: if err := e.opt.Validate(v); err != nil { lines = append(lines, stError.Render("✗ "+err.Error())) } else { lines = append(lines, stOK.Render("✓ valid")) } } if e.opt.Kind == schema.KindColor || e.opt.Kind == schema.KindPalette || e.opt.Kind == schema.KindColorList { var sw []string for _, part := range strings.Split(v, ",") { if s := swatch(part); s != "" { sw = append(sw, s+s+s) } } if len(sw) > 0 { lines = append(lines, "", strings.Join(sw, " ")+" "+stDim.Render("preview")) } } if e.opt.Hint != "" { lines = append(lines, "", stDim.Render("Format: ")+e.opt.Hint) } if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric { lines = append(lines, "", stDim.Render("Use ↑/↓ to increase or decrease the value.")) } return strings.Join(lines, "\n") } func (e *textEditor) Help() string { return "type to edit · enter apply · esc cancel" } // stepValue increments or decrements numeric values, keeping a percentage // suffix for metric modifiers. func stepValue(o *schema.Option, value string, delta int) (string, bool) { v := strings.TrimSpace(schema.Unquote(value)) if v == "" { v = o.Default() } pct := strings.HasSuffix(v, "%") v = strings.TrimSuffix(v, "%") if v == "" { v = "0" } var f float64 if _, err := fmt.Sscanf(v, "%g", &f); err != nil { return "", false } step := 1.0 if o.Kind == schema.KindFloat { switch { case o.Max != nil && *o.Max <= 1: step = 0.05 case f < 1 && f > -1 && o.Key != "font-size": step = 0.1 case o.Key == "font-size": step = 0.5 } } f += float64(delta) * step if o.Min != nil && f < *o.Min { f = *o.Min } if o.Max != nil && f > *o.Max { f = *o.Max } var s string if o.Kind == schema.KindFloat { s = strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), ".") if s == "" || s == "-" { s = "0" } } else { s = fmt.Sprintf("%d", int64(f)) } if pct { s += "%" } return s, true } func contains(list []string, v string) bool { for _, s := range list { if s == v { return true } } return false }