gum/write/command.go

74 lines
1.7 KiB
Go
Raw Normal View History

package write
import (
"fmt"
"os"
2023-03-08 23:23:46 +01:00
"strings"
2022-07-20 19:39:22 +02:00
"github.com/alecthomas/kong"
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
2022-08-05 00:45:19 +02:00
2022-07-31 03:41:18 +02:00
"github.com/charmbracelet/gum/internal/exit"
"github.com/charmbracelet/gum/internal/stdin"
2022-07-20 19:39:22 +02:00
"github.com/charmbracelet/gum/style"
)
// Run provides a shell script interface for the text area bubble.
// https://github.com/charmbracelet/bubbles/textarea
func (o Options) Run() error {
in, _ := stdin.Read()
if in != "" && o.Value == "" {
o.Value = strings.ReplaceAll(in, "\r", "")
}
a := textarea.New()
a.Focus()
a.Prompt = o.Prompt
a.Placeholder = o.Placeholder
a.ShowLineNumbers = o.ShowLineNumbers
a.CharLimit = o.CharLimit
style := textarea.Style{
Base: o.BaseStyle.ToLipgloss(),
Placeholder: o.PlaceholderStyle.ToLipgloss(),
CursorLine: o.CursorLineStyle.ToLipgloss(),
CursorLineNumber: o.CursorLineNumberStyle.ToLipgloss(),
EndOfBuffer: o.EndOfBufferStyle.ToLipgloss(),
LineNumber: o.LineNumberStyle.ToLipgloss(),
Prompt: o.PromptStyle.ToLipgloss(),
}
a.BlurredStyle = style
a.FocusedStyle = style
a.Cursor.Style = o.CursorStyle.ToLipgloss()
a.SetWidth(o.Width)
2022-07-09 02:20:34 +02:00
a.SetHeight(o.Height)
a.SetValue(o.Value)
p := tea.NewProgram(model{
textarea: a,
header: o.Header,
headerStyle: o.HeaderStyle.ToLipgloss(),
}, tea.WithOutput(os.Stderr))
2022-10-18 02:23:59 +02:00
tm, err := p.Run()
2022-08-05 00:45:19 +02:00
if err != nil {
return fmt.Errorf("failed to run write: %w", err)
}
2022-07-31 03:41:18 +02:00
m := tm.(model)
if m.aborted {
return exit.ErrAborted
}
fmt.Println(m.textarea.Value())
2022-08-05 00:45:19 +02:00
return nil
}
2022-07-20 19:39:22 +02:00
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
2022-08-05 00:45:19 +02:00
style.HideFlags(ctx)
return nil
2022-07-20 19:39:22 +02:00
}