1package tui
2
3import (
4 "strconv"
5
6 "charm.land/bubbles/v2/textinput"
7 tea "charm.land/bubbletea/v2"
8 "charm.land/lipgloss/v2"
9)
10
11// Login holds the state for the login/add account form.
12type Login struct {
13 focusIndex int
14 inputs []textinput.Model
15 showCustom bool // Show custom server fields
16 useOAuth2 bool // Use OAuth2 instead of password (for gmail)
17 isEditMode bool // Whether we're editing an existing account
18 accountID string
19 hideTips bool
20 width int
21 height int
22}
23
24const (
25 inputProtocol = iota // "imap", "jmap", or "pop3"
26 inputProvider // "gmail", "icloud", or "custom"
27 inputName
28 inputEmail
29 inputFetchEmail
30 inputSendAsEmail
31 inputAuthMethod // "password" or "oauth2" (shown for gmail)
32 inputPassword
33 inputIMAPServer
34 inputIMAPPort
35 inputSMTPServer
36 inputSMTPPort
37 inputInsecure
38 inputJMAPEndpoint // JMAP session URL
39 inputPOP3Server
40 inputPOP3Port
41 inputCount
42)
43
44// NewLogin creates a new login model for adding accounts.
45func NewLogin(hideTips bool) *Login {
46 m := &Login{
47 inputs: make([]textinput.Model, inputCount),
48 hideTips: hideTips,
49 }
50
51 tiStyles := ThemedTextInputStyles()
52 var t textinput.Model
53 for i := range m.inputs {
54 t = textinput.New()
55 t.CharLimit = 128
56 t.SetStyles(tiStyles)
57
58 switch i {
59 case inputProtocol:
60 t.Placeholder = "Protocol (imap, jmap, or pop3)"
61 t.Focus()
62 t.Prompt = "🌐 > "
63 case inputProvider:
64 t.Placeholder = "Provider (gmail, outlook, icloud, or custom)"
65 t.Prompt = "🏢 > "
66 case inputName:
67 t.Placeholder = "Display Name"
68 t.Prompt = "👤 > "
69 case inputEmail:
70 t.Placeholder = "Username"
71 t.Prompt = "🏠 > "
72 case inputFetchEmail:
73 t.Placeholder = "Email Address (comma-separated for multiple)"
74 t.Prompt = "📧 > "
75 case inputSendAsEmail:
76 t.Placeholder = "Send As Email (optional From header override)"
77 t.Prompt = "✉️ > "
78 case inputAuthMethod:
79 t.Placeholder = "Auth Method (password or oauth2)"
80 t.Prompt = "🔐 > "
81 case inputPassword:
82 t.Placeholder = "Password / App Password"
83 t.EchoMode = textinput.EchoPassword
84 t.Prompt = "🔑 > "
85 case inputIMAPServer:
86 t.Placeholder = "IMAP Server (e.g., imap.example.com)"
87 t.Prompt = "📥 > "
88 case inputIMAPPort:
89 t.Placeholder = "IMAP Port (default: 993)"
90 t.Prompt = "🔢 > "
91 case inputSMTPServer:
92 t.Placeholder = "SMTP Server (e.g., smtp.example.com)"
93 t.Prompt = "📤 > "
94 case inputSMTPPort:
95 t.Placeholder = "SMTP Port (default: 587)"
96 t.Prompt = "🔢 > "
97 case inputInsecure:
98 t.Placeholder = "Insecure (true/false) - Skip TLS verification"
99 t.Prompt = "🔓 > "
100 case inputJMAPEndpoint:
101 t.Placeholder = "JMAP Session URL (e.g., https://api.fastmail.com/jmap/session)"
102 t.Prompt = "🔗 > "
103 case inputPOP3Server:
104 t.Placeholder = "POP3 Server (e.g., pop.example.com)"
105 t.Prompt = "📥 > "
106 case inputPOP3Port:
107 t.Placeholder = "POP3 Port (default: 995)"
108 t.Prompt = "🔢 > "
109 }
110 m.inputs[i] = t
111 }
112
113 return m
114}
115
116// Init initializes the login model.
117func (m *Login) Init() tea.Cmd {
118 return textinput.Blink
119}
120
121// protocol returns the currently selected protocol (defaults to "imap").
122func (m *Login) protocol() string {
123 p := m.inputs[inputProtocol].Value()
124 if p == "" {
125 return "imap"
126 }
127 return p
128}
129
130// visibleFields returns the ordered list of input indices the user should see
131// for the current protocol/provider/auth combination.
132func (m *Login) visibleFields() []int {
133 proto := m.protocol()
134 provider := m.inputs[inputProvider].Value()
135 hasOAuth := provider == "gmail" || provider == "outlook"
136
137 fields := []int{inputProtocol}
138
139 switch proto {
140 case "jmap":
141 // JMAP: no provider selector, just endpoint + common fields
142 fields = append(fields, inputName, inputEmail, inputFetchEmail, inputSendAsEmail, inputPassword, inputJMAPEndpoint)
143 case "pop3":
144 // POP3: custom server fields + SMTP for sending
145 fields = append(fields, inputName, inputEmail, inputFetchEmail, inputSendAsEmail, inputPassword,
146 inputPOP3Server, inputPOP3Port, inputSMTPServer, inputSMTPPort, inputInsecure)
147 default:
148 // IMAP (default): existing flow
149 fields = append(fields, inputProvider, inputName, inputEmail, inputFetchEmail, inputSendAsEmail)
150 if hasOAuth {
151 fields = append(fields, inputAuthMethod)
152 }
153 if !m.useOAuth2 {
154 fields = append(fields, inputPassword)
155 }
156 if m.showCustom {
157 fields = append(fields, inputIMAPServer, inputIMAPPort, inputSMTPServer, inputSMTPPort, inputInsecure)
158 }
159 }
160
161 return fields
162}
163
164// Update handles messages for the login model.
165func (m *Login) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
166 switch msg := msg.(type) {
167 case tea.WindowSizeMsg:
168 m.width = msg.Width
169 m.height = msg.Height
170 for i := range m.inputs {
171 m.inputs[i].SetWidth(msg.Width - 6)
172 }
173
174 case tea.KeyPressMsg:
175 switch msg.String() {
176 case "esc":
177 return m, func() tea.Msg { return GoToChoiceMenuMsg{} }
178
179 case "enter":
180 m.updateFlags()
181 visible := m.visibleFields()
182 lastField := visible[len(visible)-1]
183
184 if m.focusIndex == lastField {
185 return m, m.submitForm()
186 }
187 fallthrough
188
189 case "tab", "shift+tab", "up", "down":
190 s := msg.String()
191 m.updateFlags()
192 visible := m.visibleFields()
193
194 // Find current position in visible fields
195 curPos := 0
196 for i, f := range visible {
197 if f == m.focusIndex {
198 curPos = i
199 break
200 }
201 }
202
203 if s == "up" || s == "shift+tab" {
204 curPos--
205 } else {
206 curPos++
207 }
208
209 if curPos >= len(visible) {
210 curPos = 0
211 } else if curPos < 0 {
212 curPos = len(visible) - 1
213 }
214
215 m.focusIndex = visible[curPos]
216
217 cmds := make([]tea.Cmd, len(m.inputs))
218 for i := 0; i < len(m.inputs); i++ {
219 if i == m.focusIndex {
220 cmds[i] = m.inputs[i].Focus()
221 } else {
222 m.inputs[i].Blur()
223 }
224 }
225 return m, tea.Batch(cmds...)
226 }
227 }
228
229 // Update the focused input field
230 var cmds = make([]tea.Cmd, len(m.inputs))
231 for i := range m.inputs {
232 m.inputs[i], cmds[i] = m.inputs[i].Update(msg)
233 }
234
235 m.updateFlags()
236
237 return m, tea.Batch(cmds...)
238}
239
240// updateFlags recalculates showCustom and useOAuth2 from current inputs.
241func (m *Login) updateFlags() {
242 provider := m.inputs[inputProvider].Value()
243 m.showCustom = provider == "custom"
244 m.useOAuth2 = m.inputs[inputAuthMethod].Value() == "oauth2"
245}
246
247// submitForm builds and returns a Credentials message from the current inputs.
248func (m *Login) submitForm() func() tea.Msg {
249 imapPort := 993
250 smtpPort := 587
251 pop3Port := 995
252 if m.inputs[inputIMAPPort].Value() != "" {
253 if p, err := strconv.Atoi(m.inputs[inputIMAPPort].Value()); err == nil {
254 imapPort = p
255 }
256 }
257 if m.inputs[inputSMTPPort].Value() != "" {
258 if p, err := strconv.Atoi(m.inputs[inputSMTPPort].Value()); err == nil {
259 smtpPort = p
260 }
261 }
262 if m.inputs[inputPOP3Port].Value() != "" {
263 if p, err := strconv.Atoi(m.inputs[inputPOP3Port].Value()); err == nil {
264 pop3Port = p
265 }
266 }
267
268 authMethod := "password"
269 if m.useOAuth2 {
270 authMethod = "oauth2"
271 }
272
273 proto := m.protocol()
274
275 insecure := m.inputs[inputInsecure].Value() == "true"
276
277 return func() tea.Msg {
278 return Credentials{
279 Protocol: proto,
280 Provider: m.inputs[inputProvider].Value(),
281 Name: m.inputs[inputName].Value(),
282 Host: m.inputs[inputEmail].Value(),
283 FetchEmail: m.inputs[inputFetchEmail].Value(),
284 SendAsEmail: m.inputs[inputSendAsEmail].Value(),
285 Password: m.inputs[inputPassword].Value(),
286 IMAPServer: m.inputs[inputIMAPServer].Value(),
287 IMAPPort: imapPort,
288 SMTPServer: m.inputs[inputSMTPServer].Value(),
289 SMTPPort: smtpPort,
290 Insecure: insecure,
291 AuthMethod: authMethod,
292 JMAPEndpoint: m.inputs[inputJMAPEndpoint].Value(),
293 POP3Server: m.inputs[inputPOP3Server].Value(),
294 POP3Port: pop3Port,
295 }
296 }
297}
298
299// View renders the login form.
300func (m *Login) View() tea.View {
301 title := "Add Account"
302 if m.isEditMode {
303 title = "Edit Account"
304 }
305
306 proto := m.protocol()
307
308 tip := ""
309 switch m.focusIndex {
310 case inputProtocol:
311 tip = "Choose the protocol: imap (default), jmap, or pop3."
312 case inputProvider:
313 tip = "Enter your email provider (e.g., gmail, outlook, icloud) or 'custom'."
314 case inputName:
315 tip = "The name that will appear on emails you send."
316 case inputEmail:
317 tip = "Your full email address used to log in."
318 case inputFetchEmail:
319 tip = "The email address to fetch messages for (comma-separated for multiple, e.g. me@icloud.com,me@mac.com)."
320 case inputSendAsEmail:
321 tip = "Optional From header override for outgoing email. Leave blank to send as the fetched address."
322 case inputAuthMethod:
323 tip = "Type 'oauth2' for OAuth2 or 'password' for app password."
324 case inputPassword:
325 tip = "Your password or an app-specific password if using 2FA."
326 case inputIMAPServer:
327 tip = "The server address for receiving emails."
328 case inputIMAPPort:
329 tip = "The port for the IMAP server (usually 993 for SSL)."
330 case inputSMTPServer:
331 tip = "The server address for sending emails."
332 case inputSMTPPort:
333 tip = "The port for the SMTP server (usually 587 for TLS)."
334 case inputInsecure:
335 tip = "Type 'true' to disable TLS certificate verification (not recommended)."
336 case inputJMAPEndpoint:
337 tip = "The JMAP session resource URL (e.g., https://api.fastmail.com/jmap/session)."
338 case inputPOP3Server:
339 tip = "The POP3 server address for receiving emails."
340 case inputPOP3Port:
341 tip = "The port for the POP3 server (usually 995 for SSL)."
342 }
343
344 views := []string{
345 titleStyle.Render(title),
346 "Enter your email account credentials.",
347 "",
348 m.inputs[inputProtocol].View(),
349 }
350
351 switch proto {
352 case "jmap":
353 views = append(views,
354 m.inputs[inputName].View(),
355 m.inputs[inputEmail].View(),
356 m.inputs[inputFetchEmail].View(),
357 m.inputs[inputSendAsEmail].View(),
358 m.inputs[inputPassword].View(),
359 "",
360 listHeader.Render("JMAP Settings:"),
361 m.inputs[inputJMAPEndpoint].View(),
362 )
363 case "pop3":
364 views = append(views,
365 m.inputs[inputName].View(),
366 m.inputs[inputEmail].View(),
367 m.inputs[inputFetchEmail].View(),
368 m.inputs[inputSendAsEmail].View(),
369 m.inputs[inputPassword].View(),
370 "",
371 listHeader.Render("POP3 Server Settings:"),
372 m.inputs[inputPOP3Server].View(),
373 m.inputs[inputPOP3Port].View(),
374 "",
375 listHeader.Render("SMTP Settings (for sending):"),
376 m.inputs[inputSMTPServer].View(),
377 m.inputs[inputSMTPPort].View(),
378 m.inputs[inputInsecure].View(),
379 )
380 default:
381 // IMAP flow
382 provider := m.inputs[inputProvider].Value()
383 hasOAuth := provider == "gmail" || provider == "outlook"
384 views = append(views,
385 m.inputs[inputProvider].View(),
386 m.inputs[inputName].View(),
387 m.inputs[inputEmail].View(),
388 m.inputs[inputFetchEmail].View(),
389 m.inputs[inputSendAsEmail].View(),
390 )
391
392 if hasOAuth {
393 views = append(views, m.inputs[inputAuthMethod].View())
394 }
395
396 if !m.useOAuth2 {
397 views = append(views, m.inputs[inputPassword].View())
398 } else {
399 views = append(views, accountEmailStyle.Render("OAuth2 selected — browser authorization will open after submit"))
400 }
401
402 if m.showCustom {
403 customHint := accountEmailStyle.Render("Custom provider selected - configure server settings below")
404 views = append(views,
405 "",
406 customHint,
407 m.inputs[inputIMAPServer].View(),
408 m.inputs[inputIMAPPort].View(),
409 m.inputs[inputSMTPServer].View(),
410 m.inputs[inputSMTPPort].View(),
411 m.inputs[inputInsecure].View(),
412 )
413 }
414 }
415
416 views = append(views, "")
417 if !m.hideTips && tip != "" {
418 views = append(views, TipStyle.Render("Tip: "+tip))
419 }
420 views = append(views, helpStyle.Render("\nenter: save • tab: next field • esc: back to menu"))
421
422 return tea.NewView(lipgloss.JoinVertical(lipgloss.Left, views...))
423}
424
425// SetEditMode sets the login form to edit an existing account.
426func (m *Login) SetEditMode(accountID, protocol, provider, name, email, fetchEmail, sendAsEmail, imapServer string, imapPort int, smtpServer string, smtpPort int, insecure bool, jmapEndpoint, pop3Server string, pop3Port int) {
427 m.isEditMode = true
428 m.accountID = accountID
429
430 if protocol == "" {
431 protocol = "imap"
432 }
433 m.inputs[inputProtocol].SetValue(protocol)
434 m.inputs[inputProvider].SetValue(provider)
435 m.inputs[inputName].SetValue(name)
436 m.inputs[inputEmail].SetValue(email)
437 m.inputs[inputFetchEmail].SetValue(fetchEmail)
438 m.inputs[inputSendAsEmail].SetValue(sendAsEmail)
439 m.showCustom = provider == "custom"
440
441 if m.showCustom {
442 m.inputs[inputIMAPServer].SetValue(imapServer)
443 if insecure {
444 m.inputs[inputInsecure].SetValue("true")
445 } else {
446 m.inputs[inputInsecure].SetValue("false")
447 }
448 if imapPort != 0 {
449 m.inputs[inputIMAPPort].SetValue(strconv.Itoa(imapPort))
450 }
451 m.inputs[inputSMTPServer].SetValue(smtpServer)
452 if smtpPort != 0 {
453 m.inputs[inputSMTPPort].SetValue(strconv.Itoa(smtpPort))
454 }
455 }
456
457 if jmapEndpoint != "" {
458 m.inputs[inputJMAPEndpoint].SetValue(jmapEndpoint)
459 }
460 if pop3Server != "" {
461 m.inputs[inputPOP3Server].SetValue(pop3Server)
462 }
463 if pop3Port != 0 {
464 m.inputs[inputPOP3Port].SetValue(strconv.Itoa(pop3Port))
465 }
466 // Also set SMTP for POP3
467 if protocol == "pop3" {
468 m.inputs[inputSMTPServer].SetValue(smtpServer)
469 if smtpPort != 0 {
470 m.inputs[inputSMTPPort].SetValue(strconv.Itoa(smtpPort))
471 }
472 }
473}
474
475// GetAccountID returns the account ID being edited (if in edit mode).
476func (m *Login) GetAccountID() string {
477 return m.accountID
478}
479
480// IsEditMode returns whether the form is in edit mode.
481func (m *Login) IsEditMode() bool {
482 return m.isEditMode
483}