1package tui
2
3import (
4 "fmt"
5 "sort"
6 "strings"
7
8 "charm.land/bubbles/v2/key"
9 "charm.land/bubbles/v2/list"
10 tea "charm.land/bubbletea/v2"
11 "charm.land/lipgloss/v2"
12 "github.com/floatpane/matcha/config"
13 "github.com/floatpane/matcha/fetcher"
14)
15
16const sidebarWidth = 25
17
18var (
19 sidebarStyle = lipgloss.NewStyle().
20 Width(sidebarWidth).
21 BorderStyle(lipgloss.NormalBorder()).
22 BorderRight(true).
23 PaddingRight(1).
24 PaddingLeft(1)
25
26 sidebarTitleStyle = lipgloss.NewStyle().
27 Foreground(lipgloss.Color("42")).
28 Bold(true).
29 PaddingBottom(1)
30
31 folderStyle = lipgloss.NewStyle().
32 PaddingLeft(1).
33 PaddingRight(1)
34
35 activeFolderStyle = lipgloss.NewStyle().
36 PaddingLeft(1).
37 PaddingRight(1).
38 Background(lipgloss.Color("42")).
39 Foreground(lipgloss.Color("#000000")).
40 Bold(true)
41
42 moveOverlayStyle = lipgloss.NewStyle().
43 Border(lipgloss.RoundedBorder()).
44 BorderForeground(lipgloss.Color("#25A065")).
45 Padding(1, 2)
46
47 moveOverlayTitleStyle = lipgloss.NewStyle().
48 Foreground(lipgloss.Color("42")).
49 Bold(true).
50 PaddingBottom(1)
51
52 moveItemStyle = lipgloss.NewStyle().
53 PaddingLeft(1)
54
55 moveSelectedItemStyle = lipgloss.NewStyle().
56 PaddingLeft(1).
57 Foreground(lipgloss.Color("42")).
58 Bold(true)
59)
60
61// FolderInbox combines a folder sidebar with an email list.
62type FolderInbox struct {
63 folders []string
64 activeFolderIdx int
65 currentFolder string
66 inbox *Inbox
67 accounts []config.Account
68 width int
69 height int
70 isLoadingEmails bool
71
72 // Move-to-folder overlay state
73 movingEmail bool
74 moveTargetIdx int
75 moveUID uint32 // Legacy: single UID
76 moveUIDs []uint32 // Batch: multiple UIDs
77 moveAccountID string
78 moveSourceFolder string
79}
80
81// sortFolders sorts folder names with INBOX always first, then alphabetically.
82func sortFolders(folders []string) []string {
83 sorted := make([]string, len(folders))
84 copy(sorted, folders)
85 sort.SliceStable(sorted, func(i, j int) bool {
86 iUpper := strings.ToUpper(sorted[i])
87 jUpper := strings.ToUpper(sorted[j])
88 if iUpper == "INBOX" {
89 return true
90 }
91 if jUpper == "INBOX" {
92 return false
93 }
94 return sorted[i] < sorted[j]
95 })
96 return sorted
97}
98
99// SetDateFormat propagates the configured date layout to the inner inbox.
100func (m *FolderInbox) SetDateFormat(layout string) {
101 if m.inbox != nil {
102 m.inbox.SetDateFormat(layout)
103 }
104}
105
106// NewFolderInbox creates a new FolderInbox with the given folders and accounts.
107func NewFolderInbox(folders []string, accounts []config.Account) *FolderInbox {
108 folders = sortFolders(folders)
109 currentFolder := "INBOX"
110 if len(folders) > 0 {
111 currentFolder = folders[0]
112 }
113
114 inbox := NewInbox(nil, accounts)
115 inbox.SetFolderName(currentFolder)
116 inbox.extraShortHelpKeys = []key.Binding{
117 key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "next folder")),
118 key.NewBinding(key.WithKeys("shift+tab"), key.WithHelp("shift+tab", "prev folder")),
119 key.NewBinding(key.WithKeys("m"), key.WithHelp("m", "move")),
120 }
121
122 return &FolderInbox{
123 folders: folders,
124 activeFolderIdx: 0,
125 currentFolder: currentFolder,
126 inbox: inbox,
127 accounts: accounts,
128 }
129}
130
131func (m *FolderInbox) Init() tea.Cmd {
132 return nil
133}
134
135func (m *FolderInbox) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
136 // If move overlay is active, handle its input
137 if m.movingEmail {
138 return m.updateMoveOverlay(msg)
139 }
140
141 switch msg := msg.(type) {
142 case tea.KeyPressMsg:
143 // Don't intercept keys while filtering
144 if m.inbox.list.FilterState() == list.Filtering {
145 break
146 }
147 switch msg.String() {
148 case "tab":
149 m.activeFolderIdx++
150 if m.activeFolderIdx >= len(m.folders) {
151 m.activeFolderIdx = 0
152 }
153 return m, m.switchFolder()
154 case "shift+tab":
155 m.activeFolderIdx--
156 if m.activeFolderIdx < 0 {
157 m.activeFolderIdx = len(m.folders) - 1
158 }
159 return m, m.switchFolder()
160 case "m":
161 // Start move-to-folder flow
162 if m.inbox.visualMode && len(m.inbox.selectedUIDs) > 0 {
163 // Batch move
164 m.movingEmail = true
165 m.moveTargetIdx = 0
166 m.moveUIDs = make([]uint32, len(m.inbox.selectionOrder))
167 copy(m.moveUIDs, m.inbox.selectionOrder)
168 m.moveAccountID = ""
169 for _, acctID := range m.inbox.selectedUIDs {
170 m.moveAccountID = acctID
171 break
172 }
173 m.moveSourceFolder = m.currentFolder
174 return m, nil
175 } else {
176 // Single move
177 selectedItem, ok := m.inbox.list.SelectedItem().(item)
178 if ok {
179 m.movingEmail = true
180 m.moveTargetIdx = 0
181 m.moveUID = selectedItem.uid
182 m.moveUIDs = []uint32{selectedItem.uid}
183 m.moveAccountID = selectedItem.accountID
184 m.moveSourceFolder = m.currentFolder
185 return m, nil
186 }
187 }
188 }
189
190 case tea.WindowSizeMsg:
191 m.width = msg.Width
192 m.height = msg.Height
193 inboxWidth := msg.Width - sidebarWidth - 3 // 3 for border + padding
194 if inboxWidth < 20 {
195 inboxWidth = 20
196 }
197 m.inbox.SetSize(inboxWidth, msg.Height)
198 return m, nil
199
200 case FolderEmailsFetchedMsg:
201 // Ignore stale responses for folders the user has navigated away from
202 if msg.FolderName != m.currentFolder {
203 return m, nil
204 }
205 m.isLoadingEmails = false
206 m.inbox.isFetching = false
207 m.inbox.isRefreshing = false
208 m.inbox.SetEmails(msg.Emails, m.accounts)
209 m.inbox.SetFolderName(msg.FolderName)
210 return m, nil
211
212 case FolderEmailsAppendedMsg:
213 if msg.FolderName != m.currentFolder {
214 return m, nil
215 }
216 m.inbox.isFetching = false
217 m.inbox.list.Title = m.inbox.getTitle()
218 if len(msg.Emails) == 0 {
219 if m.inbox.noMoreByAccount == nil {
220 m.inbox.noMoreByAccount = make(map[string]bool)
221 }
222 m.inbox.noMoreByAccount[msg.AccountID] = true
223 return m, nil
224 }
225 for _, email := range msg.Emails {
226 m.inbox.emailsByAccount[email.AccountID] = append(m.inbox.emailsByAccount[email.AccountID], email)
227 m.inbox.allEmails = append(m.inbox.allEmails, email)
228 }
229 m.inbox.emailCountByAcct[msg.AccountID] = len(m.inbox.emailsByAccount[msg.AccountID])
230 m.inbox.updateList()
231 return m, nil
232
233 case EmailMovedMsg:
234 if msg.Err != nil {
235 // Error handled by main model
236 return m, nil
237 }
238 m.inbox.RemoveEmail(msg.UID, msg.AccountID)
239 return m, nil
240 }
241
242 // Forward to inbox
243 var cmd tea.Cmd
244 _, cmd = m.inbox.Update(msg)
245
246 // Intercept FetchMoreEmailsMsg from inbox and convert to folder-aware version
247 if cmd != nil {
248 wrappedCmd := m.wrapInboxCmd(cmd)
249 return m, wrappedCmd
250 }
251
252 return m, cmd
253}
254
255// wrapInboxCmd intercepts messages from the inbox and adds folder context.
256func (m *FolderInbox) wrapInboxCmd(cmd tea.Cmd) tea.Cmd {
257 return func() tea.Msg {
258 msg := cmd()
259 switch inner := msg.(type) {
260 case FetchMoreEmailsMsg:
261 return FetchFolderMoreEmailsMsg{
262 Offset: inner.Offset,
263 AccountID: inner.AccountID,
264 FolderName: m.currentFolder,
265 Limit: inner.Limit,
266 }
267 case RequestRefreshMsg:
268 inner.FolderName = m.currentFolder
269 return inner
270 }
271 return msg
272 }
273}
274
275func (m *FolderInbox) updateMoveOverlay(msg tea.Msg) (tea.Model, tea.Cmd) {
276 switch msg := msg.(type) {
277 case tea.KeyPressMsg:
278 switch msg.String() {
279 case "esc":
280 m.movingEmail = false
281 return m, nil
282 case "up", "k":
283 m.moveTargetIdx--
284 if m.moveTargetIdx < 0 {
285 m.moveTargetIdx = len(m.moveFolderChoices()) - 1
286 }
287 return m, nil
288 case "down", "j":
289 m.moveTargetIdx++
290 choices := m.moveFolderChoices()
291 if m.moveTargetIdx >= len(choices) {
292 m.moveTargetIdx = 0
293 }
294 return m, nil
295 case "enter":
296 choices := m.moveFolderChoices()
297 if len(choices) > 0 && m.moveTargetIdx < len(choices) {
298 destFolder := choices[m.moveTargetIdx]
299 m.movingEmail = false
300
301 if len(m.moveUIDs) > 1 {
302 // Batch move
303 uids := m.moveUIDs
304 m.moveUIDs = nil
305
306 // Exit visual mode in inbox
307 m.inbox.visualMode = false
308 m.inbox.selectedUIDs = make(map[uint32]string)
309 m.inbox.selectionOrder = []uint32{}
310 m.inbox.updateListTitle()
311
312 return m, func() tea.Msg {
313 return BatchMoveEmailsMsg{
314 UIDs: uids,
315 AccountID: m.moveAccountID,
316 SourceFolder: m.moveSourceFolder,
317 DestFolder: destFolder,
318 }
319 }
320 } else {
321 // Single move
322 return m, func() tea.Msg {
323 return MoveEmailToFolderMsg{
324 UID: m.moveUID,
325 AccountID: m.moveAccountID,
326 SourceFolder: m.moveSourceFolder,
327 DestFolder: destFolder,
328 }
329 }
330 }
331 }
332 }
333 }
334 return m, nil
335}
336
337// moveFolderChoices returns all folders except the current one.
338func (m *FolderInbox) moveFolderChoices() []string {
339 var choices []string
340 for _, f := range m.folders {
341 if f != m.currentFolder {
342 choices = append(choices, f)
343 }
344 }
345 return choices
346}
347
348func (m *FolderInbox) switchFolder() tea.Cmd {
349 if m.activeFolderIdx >= 0 && m.activeFolderIdx < len(m.folders) {
350 m.currentFolder = m.folders[m.activeFolderIdx]
351 m.isLoadingEmails = true
352 m.inbox.SetFolderName(m.currentFolder)
353 // Clear current emails while loading
354 m.inbox.SetEmails(nil, m.accounts)
355 folder := m.currentFolder
356 return func() tea.Msg {
357 return SwitchFolderMsg{FolderName: folder}
358 }
359 }
360 return nil
361}
362
363func (m *FolderInbox) View() tea.View {
364 // Render sidebar
365 sidebar := m.renderSidebar()
366
367 // Render inbox
368 inboxView := m.inbox.View().Content
369
370 // Join horizontally
371 content := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, inboxView)
372
373 // If move overlay is active, render it on top
374 if m.movingEmail {
375 content = m.renderWithMoveOverlay(content)
376 }
377
378 return tea.NewView(content)
379}
380
381func (m *FolderInbox) renderSidebar() string {
382 var b strings.Builder
383
384 // Account name as title
385 title := "Folders"
386 if len(m.accounts) > 0 {
387 acc := m.accounts[0]
388 if acc.Name != "" {
389 title = acc.Name
390 } else if acc.FetchEmail != "" {
391 title = acc.FetchEmail
392 }
393 }
394 b.WriteString(sidebarTitleStyle.Render(title))
395 b.WriteString("\n")
396
397 for i, folder := range m.folders {
398 displayName := m.formatFolderName(folder)
399 if i == m.activeFolderIdx {
400 b.WriteString(activeFolderStyle.Width(sidebarWidth - 4).Render(displayName))
401 } else {
402 b.WriteString(folderStyle.Render(displayName))
403 }
404 if i < len(m.folders)-1 {
405 b.WriteString("\n")
406 }
407 }
408
409 sidebarHeight := m.height
410 if sidebarHeight < 1 {
411 sidebarHeight = 20
412 }
413
414 return sidebarStyle.Height(sidebarHeight - 2).Render(b.String())
415}
416
417// formatFolderName makes IMAP folder names more readable.
418func (m *FolderInbox) formatFolderName(name string) string {
419 // Strip common IMAP prefixes for cleaner display
420 name = strings.TrimPrefix(name, "[Gmail]/")
421 name = strings.TrimPrefix(name, "[Google Mail]/")
422 // Truncate to fit sidebar
423 maxLen := sidebarWidth - 5
424 if len(name) > maxLen {
425 name = name[:maxLen-1] + "\u2026"
426 }
427 return name
428}
429
430func (m *FolderInbox) renderWithMoveOverlay(content string) string {
431 choices := m.moveFolderChoices()
432 if len(choices) == 0 {
433 return content
434 }
435
436 var b strings.Builder
437 title := "Move to folder:"
438 if len(m.moveUIDs) > 1 {
439 title = fmt.Sprintf("Move %d emails to folder:", len(m.moveUIDs))
440 }
441 b.WriteString(moveOverlayTitleStyle.Render(title))
442 b.WriteString("\n")
443
444 for i, folder := range choices {
445 displayName := m.formatFolderName(folder)
446 if i == m.moveTargetIdx {
447 b.WriteString(moveSelectedItemStyle.Render("> " + displayName))
448 } else {
449 b.WriteString(moveItemStyle.Render(" " + displayName))
450 }
451 if i < len(choices)-1 {
452 b.WriteString("\n")
453 }
454 }
455
456 b.WriteString("\n\n")
457 b.WriteString(helpStyle.Render("j/k: navigate enter: move esc: cancel"))
458
459 overlay := moveOverlayStyle.Render(b.String())
460
461 // Place overlay in the center of content
462 contentLines := strings.Split(content, "\n")
463 overlayLines := strings.Split(overlay, "\n")
464 contentHeight := len(contentLines)
465 overlayHeight := len(overlayLines)
466 overlayWidth := lipgloss.Width(overlay)
467
468 startRow := (contentHeight - overlayHeight) / 2
469 if startRow < 0 {
470 startRow = 0
471 }
472 startCol := (m.width - overlayWidth) / 2
473 if startCol < 0 {
474 startCol = 0
475 }
476
477 // Overlay the box on top of the content
478 for i, overlayLine := range overlayLines {
479 row := startRow + i
480 if row >= len(contentLines) {
481 break
482 }
483 line := contentLines[row]
484 lineWidth := lipgloss.Width(line)
485
486 // Build the new line: prefix + overlay + suffix
487 if startCol >= lineWidth {
488 contentLines[row] = line + strings.Repeat(" ", startCol-lineWidth) + overlayLine
489 } else {
490 // We need to place the overlay at startCol
491 // Due to ANSI escape codes, we can't simply slice the string
492 // Instead, place the overlay line padded to the left
493 contentLines[row] = lipgloss.PlaceHorizontal(m.width, lipgloss.Center, overlayLine)
494 }
495 }
496
497 return strings.Join(contentLines, "\n")
498}
499
500// SetFolders updates the folder list.
501func (m *FolderInbox) SetFolders(folders []string) {
502 m.folders = sortFolders(folders)
503 // Keep current folder if it still exists (search sorted list)
504 found := false
505 for i, f := range m.folders {
506 if f == m.currentFolder {
507 m.activeFolderIdx = i
508 found = true
509 break
510 }
511 }
512 if !found && len(m.folders) > 0 {
513 m.activeFolderIdx = 0
514 m.currentFolder = m.folders[0]
515 }
516}
517
518// SetEmails updates the inbox emails.
519func (m *FolderInbox) SetEmails(emails []fetcher.Email, accounts []config.Account) {
520 m.accounts = accounts
521 m.inbox.SetEmails(emails, accounts)
522}
523
524// GetCurrentFolder returns the currently selected folder name.
525func (m *FolderInbox) GetCurrentFolder() string {
526 return m.currentFolder
527}
528
529// GetInbox returns the embedded inbox.
530func (m *FolderInbox) GetInbox() *Inbox {
531 return m.inbox
532}
533
534// GetAccounts returns the accounts.
535func (m *FolderInbox) GetAccounts() []config.Account {
536 return m.accounts
537}
538
539// RemoveEmail removes an email from the embedded inbox.
540func (m *FolderInbox) RemoveEmail(uid uint32, accountID string) {
541 m.inbox.RemoveEmail(uid, accountID)
542}
543
544// AdditionalShortHelpKeys returns help key bindings for the folder inbox.
545func (m *FolderInbox) AdditionalShortHelpKeys() []key.Binding {
546 return []key.Binding{
547 key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "next folder")),
548 key.NewBinding(key.WithKeys("shift+tab"), key.WithHelp("shift+tab", "prev folder")),
549 key.NewBinding(key.WithKeys("m"), key.WithHelp("m", "move to folder")),
550 }
551}
552
553// SetLoadingEmails sets the loading state.
554func (m *FolderInbox) SetLoadingEmails(loading bool) {
555 m.isLoadingEmails = loading
556 if loading {
557 m.inbox.isFetching = true
558 } else {
559 m.inbox.isFetching = false
560 }
561 m.inbox.list.Title = m.inbox.getTitle()
562}
563
564// SetRefreshing sets the refreshing state (used when user presses "r").
565func (m *FolderInbox) SetRefreshing(refreshing bool) {
566 m.inbox.isRefreshing = refreshing
567 m.inbox.list.Title = m.inbox.getTitle()
568}
569
570// GetFolders returns the current folder list.
571func (m *FolderInbox) GetFolders() []string {
572 return m.folders
573}
574
575// Helper to get the formatted inbox title
576func folderInboxTitle(folder string) string {
577 return fmt.Sprintf("Folder: %s", folder)
578}