-
Notifications
You must be signed in to change notification settings - Fork 9
/
ask.go
114 lines (90 loc) · 2.36 KB
/
ask.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package tui
import (
"context"
"fmt"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/muesli/reflow/wordwrap"
"namespacelabs.dev/foundation/internal/console"
)
func Ask(ctx context.Context, title, description, placeholder string) (string, error) {
done := console.EnterInputMode(ctx)
defer done()
p := tea.NewProgram(initialAskModel(title, description, placeholder))
final, err := p.Run()
if err != nil {
return "", err
}
if final.(askModel).canceled {
return "", nil
}
res := final.(askModel).textInput.Value()
if res == "" {
return placeholder, nil
}
return res, nil
}
type askModel struct {
title, description string
textInput textinput.Model
help help.Model
wordwrap bool
canceled bool
}
func initialAskModel(title, description, placeholder string) askModel {
ti := textinput.New()
ti.Placeholder = placeholder
ti.Focus()
ti.Width = 64
help := help.New()
return askModel{
title: title,
description: description,
textInput: ti,
help: help,
wordwrap: true,
}
}
func (m askModel) Init() tea.Cmd {
return nil
}
func (m askModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEnter:
return m, tea.Quit
case tea.KeyCtrlC, tea.KeyEsc:
m.canceled = true
return m, tea.Quit
}
case tea.WindowSizeMsg:
m.wordwrap = msg.Width > 80
m.textInput.Width = msg.Width - 5
}
m.textInput, cmd = m.textInput.Update(msg)
return m, cmd
}
func (m askModel) View() string {
body := fmt.Sprintf("%s\n\n%s\n", titleStyle.Render(m.title), descStyle.Render(m.description))
if m.wordwrap {
body = wordwrap.String(body, 80)
}
return askMainStyle.Render(fmt.Sprintf("%s\n%s\n\n%s", body, m.textInput.View(), m.help.View(escOnly{})))
}
type escOnly struct{}
func (escOnly) ShortHelp() []key.Binding {
return []key.Binding{
key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "quit"),
),
}
}
func (escOnly) FullHelp() [][]key.Binding { return nil }