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 "ctrl+v":
180 // Toggle password visibility while focused on the password field,
181 // so typos in app-passwords are catchable without retyping.
182 if m.focusIndex == inputPassword {
183 if m.inputs[inputPassword].EchoMode == textinput.EchoPassword {
184 m.inputs[inputPassword].EchoMode = textinput.EchoNormal
185 } else {
186 m.inputs[inputPassword].EchoMode = textinput.EchoPassword
187 }
188 return m, nil
189 }
190
191 case "enter":
192 m.updateFlags()
193 visible := m.visibleFields()
194 lastField := visible[len(visible)-1]
195
196 if m.focusIndex == lastField {
197 return m, m.submitForm()
198 }
199 fallthrough
200
201 case "tab", "shift+tab", "up", "down":
202 s := msg.String()
203 m.updateFlags()
204 visible := m.visibleFields()
205
206 // Find current position in visible fields
207 curPos := 0
208 for i, f := range visible {
209 if f == m.focusIndex {
210 curPos = i
211 break
212 }
213 }
214
215 if s == "up" || s == "shift+tab" {
216 curPos--
217 } else {
218 curPos++
219 }
220
221 if curPos >= len(visible) {
222 curPos = 0
223 } else if curPos < 0 {
224 curPos = len(visible) - 1
225 }
226
227 m.focusIndex = visible[curPos]
228
229 cmds := make([]tea.Cmd, len(m.inputs))
230 for i := 0; i < len(m.inputs); i++ {
231 if i == m.focusIndex {
232 cmds[i] = m.inputs[i].Focus()
233 } else {
234 m.inputs[i].Blur()
235 }
236 }
237 return m, tea.Batch(cmds...)
238 }
239 }
240
241 // Update the focused input field
242 var cmds = make([]tea.Cmd, len(m.inputs))
243 for i := range m.inputs {
244 m.inputs[i], cmds[i] = m.inputs[i].Update(msg)
245 }
246
247 m.updateFlags()
248
249 return m, tea.Batch(cmds...)
250}
251
252// updateFlags recalculates showCustom and useOAuth2 from current inputs.
253func (m *Login) updateFlags() {
254 provider := m.inputs[inputProvider].Value()
255 m.showCustom = provider == "custom"
256 m.useOAuth2 = m.inputs[inputAuthMethod].Value() == "oauth2"
257}
258
259// validPort parses a port string and returns the integer value if it is within
260// the valid TCP/UDP port range (1-65535). Returns the fallback if the string is
261// empty or invalid.
262func validPort(s string, fallback int) int {
263 if s == "" {
264 return fallback
265 }
266 p, err := strconv.Atoi(s)
267 if err != nil || p < 1 || p > 65535 {
268 return fallback
269 }
270 return p
271}
272
273// submitForm builds and returns a Credentials message from the current inputs.
274func (m *Login) submitForm() func() tea.Msg {
275 imapPort := validPort(m.inputs[inputIMAPPort].Value(), 993)
276 smtpPort := validPort(m.inputs[inputSMTPPort].Value(), 587)
277 pop3Port := validPort(m.inputs[inputPOP3Port].Value(), 995)
278
279 authMethod := "password"
280 if m.useOAuth2 {
281 authMethod = "oauth2"
282 }
283
284 proto := m.protocol()
285
286 insecure := m.inputs[inputInsecure].Value() == "true"
287
288 return func() tea.Msg {
289 return Credentials{
290 Protocol: proto,
291 Provider: m.inputs[inputProvider].Value(),
292 Name: m.inputs[inputName].Value(),
293 Host: m.inputs[inputEmail].Value(),
294 FetchEmail: m.inputs[inputFetchEmail].Value(),
295 SendAsEmail: m.inputs[inputSendAsEmail].Value(),
296 Password: m.inputs[inputPassword].Value(),
297 IMAPServer: m.inputs[inputIMAPServer].Value(),
298 IMAPPort: imapPort,
299 SMTPServer: m.inputs[inputSMTPServer].Value(),
300 SMTPPort: smtpPort,
301 Insecure: insecure,
302 AuthMethod: authMethod,
303 JMAPEndpoint: m.inputs[inputJMAPEndpoint].Value(),
304 POP3Server: m.inputs[inputPOP3Server].Value(),
305 POP3Port: pop3Port,
306 }
307 }
308}
309
310// View renders the login form.
311func (m *Login) View() tea.View {
312 title := "Add Account"
313 if m.isEditMode {
314 title = "Edit Account"
315 }
316
317 proto := m.protocol()
318
319 tip := ""
320 switch m.focusIndex {
321 case inputProtocol:
322 tip = "Choose the protocol: imap (default), jmap, or pop3."
323 case inputProvider:
324 tip = "Enter your email provider (e.g., gmail, outlook, icloud) or 'custom'."
325 case inputName:
326 tip = "The name that will appear on emails you send."
327 case inputEmail:
328 tip = "Your full email address used to log in."
329 case inputFetchEmail:
330 tip = "The email address to fetch messages for (comma-separated for multiple, e.g. me@icloud.com,me@mac.com)."
331 case inputSendAsEmail:
332 tip = "Optional From header override for outgoing email. Leave blank to send as the fetched address."
333 case inputAuthMethod:
334 tip = "Type 'oauth2' for OAuth2 or 'password' for app password."
335 case inputPassword:
336 tip = "Your password or an app-specific password if using 2FA."
337 case inputIMAPServer:
338 tip = "The server address for receiving emails."
339 case inputIMAPPort:
340 tip = "The port for the IMAP server (usually 993 for SSL)."
341 case inputSMTPServer:
342 tip = "The server address for sending emails."
343 case inputSMTPPort:
344 tip = "The port for the SMTP server (usually 587 for TLS)."
345 case inputInsecure:
346 tip = "Type 'true' to disable TLS certificate verification (not recommended)."
347 case inputJMAPEndpoint:
348 tip = "The JMAP session resource URL (e.g., https://api.fastmail.com/jmap/session)."
349 case inputPOP3Server:
350 tip = "The POP3 server address for receiving emails."
351 case inputPOP3Port:
352 tip = "The port for the POP3 server (usually 995 for SSL)."
353 }
354
355 views := []string{
356 titleStyle.Render(title),
357 "Enter your email account credentials.",
358 "",
359 m.inputs[inputProtocol].View(),
360 }
361
362 switch proto {
363 case "jmap":
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("JMAP Settings:"),
372 m.inputs[inputJMAPEndpoint].View(),
373 )
374 case "pop3":
375 views = append(views,
376 m.inputs[inputName].View(),
377 m.inputs[inputEmail].View(),
378 m.inputs[inputFetchEmail].View(),
379 m.inputs[inputSendAsEmail].View(),
380 m.inputs[inputPassword].View(),
381 "",
382 listHeader.Render("POP3 Server Settings:"),
383 m.inputs[inputPOP3Server].View(),
384 m.inputs[inputPOP3Port].View(),
385 "",
386 listHeader.Render("SMTP Settings (for sending):"),
387 m.inputs[inputSMTPServer].View(),
388 m.inputs[inputSMTPPort].View(),
389 m.inputs[inputInsecure].View(),
390 )
391 default:
392 // IMAP flow
393 provider := m.inputs[inputProvider].Value()
394 hasOAuth := provider == "gmail" || provider == "outlook"
395 views = append(views,
396 m.inputs[inputProvider].View(),
397 m.inputs[inputName].View(),
398 m.inputs[inputEmail].View(),
399 m.inputs[inputFetchEmail].View(),
400 m.inputs[inputSendAsEmail].View(),
401 )
402
403 if hasOAuth {
404 views = append(views, m.inputs[inputAuthMethod].View())
405 }
406
407 if !m.useOAuth2 {
408 views = append(views, m.inputs[inputPassword].View())
409 } else {
410 views = append(views, accountEmailStyle.Render("OAuth2 selected — browser authorization will open after submit"))
411 }
412
413 if m.showCustom {
414 customHint := accountEmailStyle.Render("Custom provider selected - configure server settings below")
415 views = append(views,
416 "",
417 customHint,
418 m.inputs[inputIMAPServer].View(),
419 m.inputs[inputIMAPPort].View(),
420 m.inputs[inputSMTPServer].View(),
421 m.inputs[inputSMTPPort].View(),
422 m.inputs[inputInsecure].View(),
423 )
424 }
425 }
426
427 views = append(views, "")
428 if !m.hideTips && tip != "" {
429 views = append(views, TipStyle.Render("Tip: "+tip))
430 }
431 helpLine := "enter: save • tab: next field • esc: back to menu"
432 if m.focusIndex == inputPassword {
433 helpLine += " • ctrl+v: toggle password visibility"
434 }
435 views = append(views, helpStyle.Render("\n"+helpLine))
436
437 return tea.NewView(lipgloss.JoinVertical(lipgloss.Left, views...))
438}
439
440// SetEditMode sets the login form to edit an existing account.
441func (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) {
442 m.isEditMode = true
443 m.accountID = accountID
444
445 if protocol == "" {
446 protocol = "imap"
447 }
448 m.inputs[inputProtocol].SetValue(protocol)
449 m.inputs[inputProvider].SetValue(provider)
450 m.inputs[inputName].SetValue(name)
451 m.inputs[inputEmail].SetValue(email)
452 m.inputs[inputFetchEmail].SetValue(fetchEmail)
453 m.inputs[inputSendAsEmail].SetValue(sendAsEmail)
454 m.showCustom = provider == "custom"
455
456 if m.showCustom {
457 m.inputs[inputIMAPServer].SetValue(imapServer)
458 if insecure {
459 m.inputs[inputInsecure].SetValue("true")
460 } else {
461 m.inputs[inputInsecure].SetValue("false")
462 }
463 if imapPort != 0 {
464 m.inputs[inputIMAPPort].SetValue(strconv.Itoa(imapPort))
465 }
466 m.inputs[inputSMTPServer].SetValue(smtpServer)
467 if smtpPort != 0 {
468 m.inputs[inputSMTPPort].SetValue(strconv.Itoa(smtpPort))
469 }
470 }
471
472 if jmapEndpoint != "" {
473 m.inputs[inputJMAPEndpoint].SetValue(jmapEndpoint)
474 }
475 if pop3Server != "" {
476 m.inputs[inputPOP3Server].SetValue(pop3Server)
477 }
478 if pop3Port != 0 {
479 m.inputs[inputPOP3Port].SetValue(strconv.Itoa(pop3Port))
480 }
481 // Also set SMTP for POP3
482 if protocol == "pop3" {
483 m.inputs[inputSMTPServer].SetValue(smtpServer)
484 if smtpPort != 0 {
485 m.inputs[inputSMTPPort].SetValue(strconv.Itoa(smtpPort))
486 }
487 }
488}
489
490// GetAccountID returns the account ID being edited (if in edit mode).
491func (m *Login) GetAccountID() string {
492 return m.accountID
493}
494
495// IsEditMode returns whether the form is in edit mode.
496func (m *Login) IsEditMode() bool {
497 return m.isEditMode
498}