Skip to content
Myr

command.go

This file

Path

write/command.go

87 lines · 2.2 KiB · Go

Last changed by

feat: adding --padding to most commands (#960)Carlos Alexandro Beckerbefore adoption6045525

History of this file

Take it

1package write23import (4	"errors"5	"fmt"6	"os"7	"strings"89	"github.com/charmbracelet/bubbles/help"10	"github.com/charmbracelet/bubbles/textarea"11	tea "github.com/charmbracelet/bubbletea"12	"github.com/charmbracelet/gum/cursor"13	"github.com/charmbracelet/gum/internal/stdin"14	"github.com/charmbracelet/gum/internal/timeout"15	"github.com/charmbracelet/gum/style"16)1718// Run provides a shell script interface for the text area bubble.19// https://github.com/charmbracelet/bubbles/textarea20func (o Options) Run() error {21	in, _ := stdin.Read(stdin.StripANSI(o.StripANSI))22	if in != "" && o.Value == "" {23		o.Value = strings.ReplaceAll(in, "\r", "")24	}2526	a := textarea.New()27	a.Focus()2829	a.Prompt = o.Prompt30	a.Placeholder = o.Placeholder31	a.ShowLineNumbers = o.ShowLineNumbers32	a.CharLimit = o.CharLimit33	a.MaxHeight = o.MaxLines34	top, right, bottom, left := style.ParsePadding(o.Padding)3536	style := textarea.Style{37		Base:             o.BaseStyle.ToLipgloss(),38		Placeholder:      o.PlaceholderStyle.ToLipgloss(),39		CursorLine:       o.CursorLineStyle.ToLipgloss(),40		CursorLineNumber: o.CursorLineNumberStyle.ToLipgloss(),41		EndOfBuffer:      o.EndOfBufferStyle.ToLipgloss(),42		LineNumber:       o.LineNumberStyle.ToLipgloss(),43		Prompt:           o.PromptStyle.ToLipgloss(),44	}4546	a.BlurredStyle = style47	a.FocusedStyle = style48	a.Cursor.Style = o.CursorStyle.ToLipgloss()49	a.Cursor.SetMode(cursor.Modes[o.CursorMode])5051	a.SetWidth(max(0, o.Width-left-right))52	a.SetHeight(max(0, o.Height-top-bottom))53	a.SetValue(o.Value)5455	m := model{56		textarea:    a,57		header:      o.Header,58		headerStyle: o.HeaderStyle.ToLipgloss(),59		autoWidth:   o.Width < 1,60		help:        help.New(),61		showHelp:    o.ShowHelp,62		keymap:      defaultKeymap(),63		padding:     []int{top, right, bottom, left},64	}6566	m.textarea.KeyMap.InsertNewline = m.keymap.InsertNewline6768	ctx, cancel := timeout.Context(o.Timeout)69	defer cancel()7071	p := tea.NewProgram(72		m,73		tea.WithOutput(os.Stderr),74		tea.WithReportFocus(),75		tea.WithContext(ctx),76	)77	tm, err := p.Run()78	if err != nil {79		return fmt.Errorf("failed to run write: %w", err)80	}81	m = tm.(model)82	if !m.submitted {83		return errors.New("not submitted")84	}85	fmt.Println(m.textarea.Value())86	return nil87}