refactor: Use Default Value in confirm as timeout value

This commit is contained in:
Dieter Eickstaedt 2023-01-08 08:52:53 +01:00
parent d2e9e37f89
commit 02d0bf4dbc
2 changed files with 26 additions and 9 deletions

View file

@ -17,6 +17,7 @@ func (o Options) Run() error {
affirmative: o.Affirmative, affirmative: o.Affirmative,
negative: o.Negative, negative: o.Negative,
confirmation: o.Default, confirmation: o.Default,
defvalue: o.Default,
timeout: o.Timeout, timeout: o.Timeout,
hasTimeout: o.HasTimeout(), hasTimeout: o.HasTimeout(),
prompt: o.Prompt, prompt: o.Prompt,

View file

@ -18,6 +18,10 @@ import (
"github.com/charmbracelet/lipgloss" "github.com/charmbracelet/lipgloss"
) )
type defaultVal struct {
Value bool
}
type model struct { type model struct {
prompt string prompt string
affirmative string affirmative string
@ -27,6 +31,7 @@ type model struct {
hasTimeout bool hasTimeout bool
timeout time.Duration timeout time.Duration
confirmation bool confirmation bool
defvalue bool
// styles // styles
promptStyle lipgloss.Style promptStyle lipgloss.Style
selectedStyle lipgloss.Style selectedStyle lipgloss.Style
@ -34,7 +39,7 @@ type model struct {
} }
func (m model) Init() tea.Cmd { func (m model) Init() tea.Cmd {
return timeout.Init(m.timeout, m.confirmation) return timeout.Init(m.timeout, defaultVal{Value: m.confirmation})
} }
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
@ -67,9 +72,15 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit return m, tea.Quit
} }
case timeout.TimeoutMsg: case timeout.TimeoutMsg:
if msg.TimeoutValue <= 0 { if msg.TimeoutValue <= 0 {
m.quitting = true m.quitting = true
if v, ok := msg.Data.(defaultVal); ok {
m.confirmation = v.Value
} else {
m.confirmation = false m.confirmation = false
}
return m, tea.Quit return m, tea.Quit
} }
@ -84,18 +95,23 @@ func (m model) View() string {
return "" return ""
} }
var aff, neg, timeoutStr string var aff, neg, timeoutStrYes, timeoutStrNo string
timeoutStrNo = ""
timeoutStrYes = ""
if m.hasTimeout { if m.hasTimeout {
timeoutStr = timeout.TimeoutStr(m.timeout) if m.defvalue {
timeoutStrYes = timeout.TimeoutStr(m.timeout)
} else {
timeoutStrNo = timeout.TimeoutStr(m.timeout)
}
} }
if m.confirmation { if m.confirmation {
aff = m.selectedStyle.Render(m.affirmative) aff = m.selectedStyle.Render(m.affirmative + timeoutStrYes)
neg = m.unselectedStyle.Render(m.negative + timeoutStr) neg = m.unselectedStyle.Render(m.negative + timeoutStrNo)
} else { } else {
aff = m.unselectedStyle.Render(m.affirmative) aff = m.unselectedStyle.Render(m.affirmative + timeoutStrYes)
neg = m.selectedStyle.Render(m.negative + timeoutStr) neg = m.selectedStyle.Render(m.negative + timeoutStrNo)
} }
// If the option is intentionally empty, do not show it. // If the option is intentionally empty, do not show it.