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