Skip to content

Commit

Permalink
feat(form): implement WithTimeout (#276)
Browse files Browse the repository at this point in the history
* feat(form): implement WithTimeout

* fix: no timeout

---------

Co-authored-by: Maas Lalani <maas@lalani.dev>
  • Loading branch information
Delta456 and maaslalani committed Jun 8, 2024
1 parent 463dcbc commit 5b41f0b
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions form.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package huh

import (
"context"
"errors"
"io"
"os"
"time"

"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
Expand All @@ -30,6 +32,9 @@ const (
// ErrUserAborted is the error returned when a user exits the form before submitting.
var ErrUserAborted = errors.New("user aborted")

// ErrTimeout is the error returned when the timeout is reached.
var ErrTimeout = errors.New("timeout")

// Form is a collection of groups that are displayed one at a time on a "page".
//
// The form can navigate between groups and is complete once all the groups are
Expand Down Expand Up @@ -61,6 +66,7 @@ type Form struct {
width int
height int
keymap *KeyMap
timeout time.Duration
teaOptions []tea.ProgramOption

layout Layout
Expand Down Expand Up @@ -299,6 +305,12 @@ func (f *Form) WithInput(r io.Reader) *Form {
return f
}

// WithTimeout sets the duration for the form to be killed.
func (f *Form) WithTimeout(t time.Duration) *Form {
f.timeout = t
return f
}

// WithProgramOptions sets the tea options of the form.
func (f *Form) WithProgramOptions(opts ...tea.ProgramOption) *Form {
f.teaOptions = opts
Expand Down Expand Up @@ -590,10 +602,19 @@ func (f *Form) Run() error {

// run runs the form in normal mode.
func (f *Form) run() error {
startTime := time.Now()
if f.timeout > 0 {
ctx, cancel := context.WithTimeout(context.Background(), f.timeout)
defer cancel()
f.teaOptions = append(f.teaOptions, tea.WithContext(ctx))
}
m, err := tea.NewProgram(f, f.teaOptions...).Run()
if m.(*Form).aborted {
err = ErrUserAborted
}
if err != nil && time.Since(startTime) >= f.timeout {
err = ErrTimeout
}
return err
}

Expand Down

0 comments on commit 5b41f0b

Please sign in to comment.