Skip to content

Commit

Permalink
Spinner contexts (#33)
Browse files Browse the repository at this point in the history
* feat: pass context to spinner

* fix: lint

* fix: use allocated memory

* fix: lint gomnd
  • Loading branch information
maaslalani authored Nov 9, 2023
1 parent 9250f9d commit 228ef28
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 28 deletions.
6 changes: 4 additions & 2 deletions field_confirm.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/charmbracelet/lipgloss"
)

const choiceConfirmation = "Chose: "

// Confirm is a form confirm field.
type Confirm struct {
value *bool
Expand Down Expand Up @@ -179,9 +181,9 @@ func (c *Confirm) runAccessible() error {
choice := accessibility.PromptBool()
*c.value = choice
if choice {
fmt.Println(c.theme.Focused.SelectedOption.Render("Chose: " + c.affirmative))
fmt.Println(c.theme.Focused.SelectedOption.Render(choiceConfirmation + c.affirmative))
} else {
fmt.Println(c.theme.Focused.SelectedOption.Render("Chose: " + c.negative))
fmt.Println(c.theme.Focused.SelectedOption.Render(choiceConfirmation + c.negative))
}
fmt.Println()
return nil
Expand Down
2 changes: 1 addition & 1 deletion field_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ func (s *Select[T]) runAccessible() error {
fmt.Println(err.Error())
continue
}
fmt.Println(s.theme.Focused.SelectedOption.Render("Chose: " + option.Key + "\n"))
fmt.Println(s.theme.Focused.SelectedOption.Render(choiceConfirmation + option.Key + "\n"))
*s.value = option.Value
break
}
Expand Down
5 changes: 1 addition & 4 deletions field_text.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,6 @@ func getEditor() (string, []string) {
//
// The first argument provided is used as the editor command (vim, nvim, nano, etc...)
// The following (optional) arguments provided are passed as arguments to the editor command.
//
// .Editor("vim")
// .Editor("vim", "+10")
func (t *Text) Editor(editor ...string) *Text {
if len(editor) > 0 {
t.editorCmd = editor[0]
Expand Down Expand Up @@ -185,7 +182,7 @@ func (t *Text) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
ext := strings.TrimPrefix(t.editorExtension, ".")
tmpFile, _ := os.CreateTemp(os.TempDir(), "*."+ext)
cmd := exec.Command(t.editorCmd, append(t.editorArgs, tmpFile.Name())...) //nolint:gosec
_ = os.WriteFile(tmpFile.Name(), []byte(t.textarea.Value()), 0600)
_ = os.WriteFile(tmpFile.Name(), []byte(t.textarea.Value()), os.ModePerm)
cmds = append(cmds, tea.ExecProcess(cmd, func(error) tea.Msg {
content, _ := os.ReadFile(tmpFile.Name())
return updateValueMsg(content)
Expand Down
10 changes: 6 additions & 4 deletions form.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ type Form struct {
keymap *KeyMap
}

const defaultWidth = 80

// NewForm returns a form with the given groups and default themes and
// keybindings.
//
Expand All @@ -73,7 +75,7 @@ func NewForm(groups ...*Group) *Form {
paginator: p,
theme: NewCharmTheme(),
keymap: NewDefaultKeyMap(),
width: 80,
width: defaultWidth,
}

// NB: If dynamic forms come into play this will need to be applied when
Expand Down Expand Up @@ -209,9 +211,9 @@ func (f *Form) WithWidth(width int) *Form {

// Init initializes the form.
func (f *Form) Init() tea.Cmd {
var cmds []tea.Cmd
for _, group := range f.groups {
cmds = append(cmds, group.Init())
cmds := make([]tea.Cmd, len(f.groups))
for i, group := range f.groups {
cmds[i] = group.Init()
}
return tea.Batch(cmds...)
}
Expand Down
9 changes: 3 additions & 6 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,12 @@ func prevField() tea.Msg {

// Init initializes the group.
func (g *Group) Init() tea.Cmd {
var cmds []tea.Cmd

for _, field := range g.fields {
cmds = append(cmds, field.Init())
cmds := make([]tea.Cmd, len(g.fields)+1)
for i, field := range g.fields {
cmds[i] = field.Init()
}

cmd := g.fields[g.paginator.Page].Focus()
cmds = append(cmds, cmd)

return tea.Batch(cmds...)
}

Expand Down
9 changes: 6 additions & 3 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ type Option[T any] struct {

// NewOptions returns new options from a list of values.
func NewOptions[T any](values ...T) []Option[T] {
var options []Option[T]
for _, o := range values {
options = append(options, Option[T]{Key: fmt.Sprint(o), Value: o})
options := make([]Option[T], len(values))
for i, o := range values {
options[i] = Option[T]{
Key: fmt.Sprint(o),
Value: o,
}
}
return options
}
Expand Down
22 changes: 22 additions & 0 deletions spinner/examples/context/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
"context"
"fmt"
"time"

"github.com/charmbracelet/huh/spinner"
)

func main() {
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)

go func() {
// Do some work.
time.Sleep(5 * time.Second)
cancelFunc()
}()

spinner.New().Context(ctx).Run()
fmt.Println("Done!")
}
21 changes: 16 additions & 5 deletions spinner/spinner.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package spinner

import (
"context"
"fmt"
"os"
"time"
Expand All @@ -21,6 +22,7 @@ import (
type Spinner struct {
spinner spinner.Model
action func()
ctx context.Context
accessible bool
output *termenv.Output
title string
Expand Down Expand Up @@ -62,6 +64,12 @@ func (s *Spinner) Action(action func()) *Spinner {
return s
}

// Context sets the context of the spinner.
func (s *Spinner) Context(ctx context.Context) *Spinner {
s.ctx = ctx
return s
}

// Style sets the style of the spinner.
func (s *Spinner) Style(style lipgloss.Style) *Spinner {
s.spinner.Style = style
Expand Down Expand Up @@ -93,6 +101,7 @@ func New() *Spinner {
title: "Loading...",
titleStyle: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#FFFDF5", Dark: "#FFFDF5"}),
output: termenv.NewOutput(os.Stdout),
ctx: nil,
}
}

Expand Down Expand Up @@ -132,12 +141,14 @@ func (s *Spinner) Run() error {
return s.runAccessible()
}

p := tea.NewProgram(s)
p := tea.NewProgram(s, tea.WithContext(s.ctx))

go func() {
s.action()
p.Quit()
}()
if s.ctx == nil {
go func() {
s.action()
p.Quit()
}()
}

_, _ = p.Run()

Expand Down
12 changes: 9 additions & 3 deletions theme.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ func (t Theme) copy() Theme {
}
}

// FieldStyles are the styles for input fields
// FieldStyles are the styles for input fields.
type FieldStyles struct {
Base lipgloss.Style
Title lipgloss.Style
Description lipgloss.Style
Help lipgloss.Style // TODO: apply help coloring in theme to help bubble
Help lipgloss.Style // XXX: apply help coloring in theme to help bubble
ErrorIndicator lipgloss.Style
ErrorMessage lipgloss.Style

Expand Down Expand Up @@ -97,13 +97,19 @@ func (f FieldStyles) copy() FieldStyles {
}
}

const buttonPaddingHorizontal = 2
const buttonPaddingVertical = 0

// NewBaseTheme returns a new base theme with general styles to be inherited by
// other themes.
func NewBaseTheme() *Theme {
var t Theme

t.FieldSeparator = lipgloss.NewStyle().SetString("\n\n")
button := lipgloss.NewStyle().Padding(0, 2).MarginRight(1)

button := lipgloss.NewStyle().
Padding(buttonPaddingVertical, buttonPaddingHorizontal).
MarginRight(1)

// Focused styles.
f := &t.Focused
Expand Down

0 comments on commit 228ef28

Please sign in to comment.