Skip to content
Myr

command.go

This file

Path

write/command.go

87 lines · 2.1 KiB · Go

Last changed by

chore: prepare v2 (#1116)Drew Smirnoffbefore adoption02d6f06

History of this file

Take it

1package write23import (4	"errors"5	"fmt"6	"os"7	"strings"89	"charm.land/bubbles/v2/help"10	"charm.land/bubbles/v2/textarea"11	tea "charm.land/bubbletea/v2"12	"charm.land/gum/v2/cursor"13	"charm.land/gum/v2/internal/stdin"14	"charm.land/gum/v2/internal/timeout"15	"charm.land/gum/v2/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	taStyles := textarea.StyleState{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	styles := a.Styles()47	styles.Focused = taStyles48	styles.Blurred = taStyles49	a.SetStyles(styles)50	cursor.TextArea(&a, o.CursorMode, o.CursorStyle)5152	a.SetWidth(max(0, o.Width-left-right))53	a.SetHeight(max(0, o.Height-top-bottom))54	a.SetValue(o.Value)5556	m := model{57		textarea:    a,58		header:      o.Header,59		headerStyle: o.HeaderStyle.ToLipgloss(),60		autoWidth:   o.Width < 1,61		help:        help.New(),62		showHelp:    o.ShowHelp,63		keymap:      defaultKeymap(),64		padding:     []int{top, right, bottom, left},65	}6667	m.textarea.KeyMap.InsertNewline = m.keymap.InsertNewline6869	ctx, cancel := timeout.Context(o.Timeout)70	defer cancel()7172	p := tea.NewProgram(73		m,74		tea.WithOutput(os.Stderr),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}