Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/MessageListView.swift3// Description: The message list of a folder or a search — conversation rows with inset selection, skeleton / empty states, configurable swipe actions4// with haptics, context menus (with a preview on iOS), VoiceOver actions, drag to folders and to other apps, floating compose button on iPhone.5import SPMailCore6import SwiftUI78struct MessageListView: View {9 @Bindable var scene: MailScene10 let composeSpace: Namespace.ID11 let compactWindow: Bool12 var onOpen: () -> Void13 @State private var moreRow: ThreadSummary?14 #if os(iOS)15 @State private var editMode = EditMode.inactive16 #else17 @Environment(\.openWindow) private var openWindow18 #endif1920 private var app: AppModel { scene.app }21 private var style: RowStyle { RowStyle(app.settings) }22 private var showRecipients: Bool {23 if case .mailbox(let id) = scene.selection, let r = scene.mailboxes.first(where: { $0.id == id })?.knownRole { return r == .sent || r == .drafts }24 return false25 }26 private var isEditing: Bool {27 #if os(iOS)28 editMode.isEditing29 #else30 false31 #endif32 }3334 var body: some View {35 @Bindable var list = scene.list36 List(selection: $list.selectedIds) {37 if showsInsights { InsightChips(scene: scene).listRowBackground(Color.clear).listRowSeparator(.hidden).listRowInsets(EdgeInsets(top: SPSpacing.xs, leading: SPSpacing.xl, bottom: SPSpacing.xs, trailing: SPSpacing.xl)).selectionDisabled() }38 if scene.search.isActive, scene.search.isOffline {39 Label("Hors ligne : recherche dans les messages déjà sur cet appareil", systemImage: "wifi.slash").font(.footnote).foregroundStyle(SPColor.warn).selectionDisabled()40 .listRowBackground(Color.clear)41 }42 ForEach(scene.rows) { row in43 rowView(row)44 .tag(row.id)45 .listRowBackground(RowSelectionBackground(isSelected: scene.list.selectedIds.contains(row.id)))46 .listRowSeparator(.hidden)47 .listRowInsets(EdgeInsets(top: 0, leading: SPSpacing.xl, bottom: 0, trailing: SPSpacing.xl))48 .task { await scene.loadMore(after: row) }49 }50 if scene.list.isLoadingMore { HStack { Spacer(); ProgressView().controlSize(.small); Spacer() }.selectionDisabled().listRowBackground(Color.clear).listRowSeparator(.hidden) }51 }52 .listStyle(.plain)53 .scrollContentBackground(.hidden)54 .background(SPColor.bg)55 .overlay {56 if scene.rows.isEmpty {57 if scene.list.isLoading || scene.search.isSearching { SkeletonRows(style: style).allowsHitTesting(false) } else if scene.search.isActive {58 SPEmptyState(icon: "magnifyingglass", title: L("Aucun résultat"))59 } else {60 SPEmptyState(icon: "tray", title: L("Aucun message"))61 }62 }63 }64 #if os(iOS)65 .overlay(alignment: .bottomTrailing) { if compactWindow, !isEditing { ComposeFAB(scene: scene, space: composeSpace) } }66 #endif67 .navigationTitle(scene.listTitle)68 #if os(macOS)69 .navigationSubtitle(scene.list.selectedIds.count > 1 ? L("\(scene.list.selectedIds.count) conversations sélectionnées") : "")70 #endif71 // an older server (no /api/next): the historical search of the folder; otherwise search is its own screen (⌘F, toolbar)72 .modifier(LegacySearch(scene: scene, enabled: !app.next.isAvailable))73 .task(id: "\(scene.currentAccount ?? "")|\(showsInsights)") { if showsInsights, let account = scene.currentAccount { await app.next.loadInsights(account: account) } }74 .task(id: "\(showsInsights)|\(app.next.aiEnabled(.triage))|\(scene.list.threads.prefix(25).map(\.id))") {75 if showsInsights, let account = scene.currentAccount { await app.next.loadTriage(account: account, emailIds: scene.list.threads.prefix(25).map(\.id)) }76 }77 .refreshable { await scene.refresh() }78 .onChange(of: scene.list.selectedIds) { _, ids in79 #if os(macOS)80 scene.didChangeSelection(); if ids.count == 1 { onOpen() }81 #else82 _ = ids83 #endif84 }85 #if os(macOS)86 .onDeleteCommand { Task { await scene.perform(.delete) } }87 .contextMenu(forSelectionType: String.self) { ids in88 if let row = scene.rows.first(where: { ids.contains($0.id) }) { RowMenu(scene: scene, row: row, ids: ids) }89 } primaryAction: { ids in90 // double-click (or Return): the conversation in its own window91 if let id = ids.first, let account = scene.currentAccount { openWindow(id: "message", value: MessageRef(account: account, emailId: id, conversation: app.settings.threaded && !scene.search.isActive)) }92 }93 #else94 .environment(\.editMode, $editMode)95 .confirmationDialog(moreRow?.email.subject ?? "", isPresented: Binding(get: { moreRow != nil }, set: { if !$0 { moreRow = nil } }), titleVisibility: .visible, presenting: moreRow) { row in96 Button("Répondre") { Task { await scene.compose(.reply(row.email)) } }97 Button("Répondre à tous") { Task { await scene.compose(.replyAll(row.email)) } }98 Button("Transférer") { Task { await scene.compose(.forward(row.email)) } }99 Button(row.anyFlagged ? L("Retirer le drapeau") : L("Ajouter un drapeau")) { Task { await scene.perform(.flag(!row.anyFlagged), on: [row.id]) } }100 Button(row.isPinned ? L("Désépingler") : L("Épingler")) { Task { await scene.perform(.pin(!row.isPinned), on: [row.id]) } }101 if app.next.has(.labels) { Button("Libellés…") { scene.next.labelPick = LabelPickRequest(keywords: row.email.keywords) { action in Task { await scene.perform(action, on: [row.id]) } } } }102 if app.next.has(.reminders), let account = scene.currentAccount { Button("Me le rappeler…") { scene.next.snoozeRequest = SnoozeRequest(account: account, emailIds: [row.id], mode: .remind) }.disabled(!app.isOnline) }103 Button("Indésirable") { Task { await scene.perform(.junk, on: [row.id]) } }104 Button("Supprimer", role: .destructive) { Task { await scene.perform(.delete, on: [row.id]) } }105 Button("Annuler", role: .cancel) {}106 }107 #endif108 .toolbar { ListToolbar(scene: scene, isEditing: isEditing, compactWindow: compactWindow) }109 }110111 private func dragItem(_ row: ThreadSummary) -> MessageDragItem {112 let account = scene.currentAccount ?? ""113 return MessageDragItem(payload: MailDrag.payload(scene.list.selectedIds.contains(row.id) ? scene.list.selectedIds : [row.id]), email: row.email) { [app] m in try await app.emlFile(for: m, account: account) }114 }115116 private func quickActions(_ row: ThreadSummary) -> [RowQuickAction] {117 #if os(macOS)118 [RowQuickAction(id: "archive", title: L("Archiver"), icon: "archivebox") { Task { await scene.perform(.archive, on: [row.id]) } },119 RowQuickAction(id: "delete", title: L("Supprimer"), icon: "trash", destructive: true) { Task { await scene.perform(.delete, on: [row.id]) } },120 RowQuickAction(id: "read", title: row.unreadCount > 0 ? L("Marquer comme lu") : L("Marquer comme non lu"), icon: row.unreadCount > 0 ? "envelope.open" : "envelope.badge") {121 Task { await scene.perform(.markRead(row.unreadCount > 0), on: [row.id]) }122 }]123 #else124 []125 #endif126 }127128 /// The smart filters sit above the inbox only (they are computed for it).129 private var showsInsights: Bool {130 guard app.next.isAvailable, !scene.search.isActive, case .mailbox(let id) = scene.selection else { return false }131 return scene.mailboxes.first { $0.id == id }?.knownRole == .inbox132 }133134 @ViewBuilder private func rowView(_ row: ThreadSummary) -> some View {135 let data = ConversationRowData(row: row, showRecipients: showRecipients).decorated(by: app.next, account: showsInsights ? scene.currentAccount : nil, emailId: row.id)136 ConversationRow(data: data, style: style, quickActions: quickActions(row))137 #if os(iOS)138 .onTapGesture { if !isEditing { scene.list.selectedIds = [row.id]; scene.didChangeSelection(); onOpen() } }139 .hoverEffect(.highlight)140 .contextMenu { RowMenu(scene: scene, row: row, ids: scene.list.selectedIds.contains(row.id) ? scene.list.selectedIds : [row.id]) } preview: { RowPreview(data: data) }141 .swipeActions(edge: .leading, allowsFullSwipe: true) { ForEach(app.settings.swipeLeading) { swipeButton($0, row) } }142 .swipeActions(edge: .trailing, allowsFullSwipe: true) { ForEach(app.settings.swipeTrailing) { swipeButton($0, row) } }143 #endif144 .draggable(dragItem(row)) { DragPreview(title: data.subject, count: scene.list.selectedIds.contains(row.id) ? scene.list.selectedIds.count : 1) }145 // VoiceOver: the row actions without the swipe146 .accessibilityAction(named: Text(row.unreadCount > 0 ? "Marquer comme lu" : "Marquer comme non lu")) { Task { await scene.perform(.markRead(row.unreadCount > 0), on: [row.id]) } }147 .accessibilityAction(named: Text(row.anyFlagged ? "Retirer le drapeau" : "Ajouter un drapeau")) { Task { await scene.perform(.flag(!row.anyFlagged), on: [row.id]) } }148 .accessibilityAction(named: Text(row.isPinned ? "Désépingler" : "Épingler")) { Task { await scene.perform(.pin(!row.isPinned), on: [row.id]) } }149 .accessibilityAction(named: Text("Archiver")) { Task { await scene.perform(.archive, on: [row.id]) } }150 .accessibilityAction(named: Text("Supprimer")) { Task { await scene.perform(.delete, on: [row.id]) } }151 .accessibilityAddTraits(scene.list.selectedIds.contains(row.id) ? .isSelected : [])152 }153154 /// One configurable swipe slot. A selection haptic marks the action (the system does not report the threshold crossing itself).155 @ViewBuilder private func swipeButton(_ action: SwipeAction, _ row: ThreadSummary) -> some View {156 switch action {157 case .none: EmptyView()158 case .readUnread:159 Button { SPHaptics.selection(); Task { await scene.perform(.markRead(row.unreadCount > 0), on: [row.id]) } } label: {160 Label(row.unreadCount > 0 ? L("Lu") : L("Non lu"), systemImage: row.unreadCount > 0 ? "envelope.open" : "envelope.badge")161 }.tint(SPColor.info)162 case .flag:163 Button { SPHaptics.selection(); Task { await scene.perform(.flag(!row.anyFlagged), on: [row.id]) } } label: { Label("Drapeau", systemImage: row.anyFlagged ? "flag.slash" : "flag") }.tint(SPColor.star)164 case .pin:165 Button { SPHaptics.selection(); Task { await scene.perform(.pin(!row.isPinned), on: [row.id]) } } label: { Label(row.isPinned ? L("Désépingler") : L("Épingler"), systemImage: row.isPinned ? "pin.slash" : "pin") }.tint(SPColor.star)166 case .archive:167 Button { SPHaptics.selection(); Task { await scene.perform(.archive, on: [row.id]) } } label: { Label("Archiver", systemImage: "archivebox") }.tint(SPColor.accent)168 case .snooze:169 Button { SPHaptics.selection(); Task { await scene.snooze(ids: [row.id]) } } label: { Label("Mettre en veille", systemImage: "clock") }.tint(SPColor.warn)170 case .delete:171 Button(role: .destructive) { SPHaptics.selection(); Task { await scene.perform(.delete, on: [row.id]) } } label: { Label("Supprimer", systemImage: "trash") }172 case .more:173 Button { SPHaptics.selection(); moreRow = row } label: { Label("Plus", systemImage: "ellipsis.circle") }.tint(SPColor.text3)174 }175 }176}177178/// The drag preview: the subject, with a count badge when several conversations travel together.179struct DragPreview: View {180 let title: String181 let count: Int182 var body: some View {183 HStack(spacing: SPSpacing.m) {184 Image(systemName: "envelope").foregroundStyle(SPColor.accent)185 Text(title).font(SPFont.callout).lineLimit(1)186 if count > 1 { Text("\(count)").font(SPFont.caption).foregroundStyle(SPColor.onAccent).padding(.horizontal, 6).padding(.vertical, 1).background(SPColor.accent, in: Capsule()) }187 }188 .padding(.horizontal, SPSpacing.l).padding(.vertical, SPSpacing.m).frame(maxWidth: 280)189 .background(SPColor.surface, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))190 }191}192193/// The preview shown above a context menu on iOS / iPadOS.194struct RowPreview: View {195 let data: ConversationRowData196 var body: some View {197 VStack(alignment: .leading, spacing: SPSpacing.m) {198 HStack(spacing: SPSpacing.m) {199 AvatarView(name: data.title, address: data.address, size: 36)200 VStack(alignment: .leading, spacing: 1) {201 Text(data.title).font(SPFont.headline).foregroundStyle(SPColor.text).lineLimit(1)202 Text(data.date.formatted(date: .abbreviated, time: .shortened)).font(SPFont.caption).foregroundStyle(SPColor.text3)203 }204 }205 Text(data.subject).font(SPFont.bodyStrong).foregroundStyle(SPColor.text).lineLimit(2)206 if !data.preview.isEmpty { Text(data.preview).font(SPFont.callout).foregroundStyle(SPColor.text2).lineLimit(8) }207 }208 .padding(SPSpacing.xl).frame(width: 320, alignment: .leading)209 .background(SPColor.surface)210 }211}212213#if os(iOS)214/// The floating compose button of the iPhone list: within reach of the thumb, 56 pt, source of the composer's zoom transition.215struct ComposeFAB: View {216 let scene: MailScene217 let space: Namespace.ID218 var body: some View {219 Button { SPHaptics.impact(); Task { await scene.compose(.new) } } label: {220 Image(systemName: "square.and.pencil").font(.title3.weight(.semibold)).foregroundStyle(SPColor.onAccent)221 .frame(width: 56, height: 56).background(SPColor.accent, in: Circle())222 .spElevation(2)223 }224 .dynamicTypeSize(...DynamicTypeSize.xxxLarge) // the glyph stays inside its 56 pt circle225 .matchedTransitionSource(id: "compose", in: space)226 .padding(.trailing, SPSpacing.xxl).padding(.bottom, SPSpacing.xxl)227 .accessibilityLabel(Text("Nouveau message")) // ⌘N: « Nouveau message » of the menu commands (declared once)228 }229}230#endif231232/// Context menu of a row. Acts on the whole selection when the row is part of it.233struct RowMenu: View {234 let scene: MailScene235 let row: ThreadSummary236 let ids: Set<String>237 #if os(macOS)238 @Environment(\.openWindow) private var openWindow239 #endif240241 var body: some View {242 if ids.count == 1 {243 Button { Task { await scene.compose(.reply(row.email)) } } label: { Label("Répondre", systemImage: "arrowshape.turn.up.left") }244 Button { Task { await scene.compose(.replyAll(row.email)) } } label: { Label("Répondre à tous", systemImage: "arrowshape.turn.up.left.2") }245 Button { Task { await scene.compose(.forward(row.email)) } } label: { Label("Transférer", systemImage: "arrowshape.turn.up.right") }246 #if os(macOS)247 if let account = scene.currentAccount {248 Divider()249 Button { openWindow(id: "message", value: MessageRef(account: account, emailId: row.id, conversation: scene.app.settings.threaded && !scene.search.isActive)) } label: { Label("Ouvrir dans une nouvelle fenêtre", systemImage: "macwindow.badge.plus") }250 }251 #endif252 Divider()253 }254 Button { Task { await scene.perform(.markRead(row.unreadCount > 0), on: ids) } } label: { Label(row.unreadCount > 0 ? L("Marquer comme lu") : L("Marquer comme non lu"), systemImage: "envelope.badge") }255 Button { Task { await scene.perform(.flag(!row.anyFlagged), on: ids) } } label: { Label(row.anyFlagged ? L("Retirer le drapeau") : L("Ajouter un drapeau"), systemImage: "flag") }256 NextMenuItems(scene: scene, account: scene.currentAccount, ids: ids, keywords: Array(Set(scene.rows.filter { ids.contains($0.id) }.flatMap(\.email.keywords)))) { action in Task { await scene.perform(action, on: ids) } }257 Button { Task { await scene.perform(.archive, on: ids) } } label: { Label("Archiver", systemImage: "archivebox") }258 Menu { MoveMenuItems(scene: scene, account: scene.currentAccount, ids: ids) } label: { Label("Déplacer vers", systemImage: "folder") }259 Button { Task { await scene.perform(.junk, on: ids) } } label: { Label("Indésirable", systemImage: "xmark.bin") }260 Divider()261 Button(role: .destructive) { Task { await scene.perform(.delete, on: ids) } } label: { Label("Supprimer", systemImage: "trash") }262 }263}264265/// « Déplacer vers »: the folders of the mailbox that HOLDS the messages — `account` — which is not the window's mailbox when the266/// message was opened from the unified list or in its own window.267struct MoveMenuItems: View {268 let scene: MailScene269 let account: String?270 /// nil: the current selection.271 let ids: Set<String>?272 var body: some View {273 ForEach(scene.app.mailboxes(for: account).filter { $0.knownRole != .drafts && !$0.isSnoozedFolder }) { m in274 Button { Task { await scene.perform(.move(m.id), on: ids) } } label: { Label(MailScene.title(of: m), systemImage: MailScene.icon(of: m)) }275 }276 }277}278279struct ListToolbar: ToolbarContent {280 let scene: MailScene281 let isEditing: Bool282 let compactWindow: Bool283284 var body: some ToolbarContent {285 #if os(macOS)286 ToolbarItem(placement: .primaryAction) {287 Button { Task { await scene.compose(.new) } } label: { Label("Nouveau message", systemImage: "square.and.pencil") }.help("Nouveau message (⌘N)")288 }289 if scene.app.next.isAvailable {290 ToolbarItem(placement: .primaryAction) {291 Button { scene.openSearch() } label: { Label("Rechercher", systemImage: "magnifyingglass") }.help("Rechercher dans le courrier (⌘F)")292 }293 }294 #else295 if !compactWindow {296 ToolbarItem(placement: .primaryAction) {297 Button { Task { await scene.compose(.new) } } label: { Label("Nouveau message", systemImage: "square.and.pencil") }298 }299 }300 if scene.app.next.isAvailable { ToolbarItem(placement: .topBarTrailing) { Button { scene.openSearch() } label: { Label("Rechercher", systemImage: "magnifyingglass") } } }301 ToolbarItem(placement: .topBarTrailing) { EditButton() }302 if isEditing {303 ToolbarItemGroup(placement: .bottomBar) {304 Button { Task { await scene.toggleRead() } } label: { Label("Lu / non lu", systemImage: "envelope.badge") }305 Spacer()306 Button { Task { await scene.toggleFlag() } } label: { Label("Drapeau", systemImage: "flag") }307 Spacer()308 Menu { MoveMenuItems(scene: scene, account: scene.currentAccount, ids: nil) } label: { Label("Déplacer", systemImage: "folder") }309 Spacer()310 Button { Task { await scene.perform(.archive) } } label: { Label("Archiver", systemImage: "archivebox") }311 Spacer()312 Button(role: .destructive) { Task { await scene.perform(.delete) } } label: { Label("Supprimer", systemImage: "trash") }313 Spacer()314 Menu {315 NextMenuItems(scene: scene, account: scene.currentAccount, ids: scene.list.selectedIds, keywords: scene.selectionKeywords) { action in Task { await scene.perform(action) } }316 } label: { Label("Plus", systemImage: "ellipsis.circle") }.disabled(!scene.hasSelection)317 }318 }319 #endif320 }321}322323/// The historical search of the folder list (`Email/query` through the engine, local cache offline), kept for a server without `/api/next`.324struct LegacySearch: ViewModifier {325 @Bindable var scene: MailScene326 let enabled: Bool327 @FocusState private var searchFocused: Bool328329 func body(content: Content) -> some View {330 @Bindable var search = scene.search331 if enabled {332 content333 .searchable(text: $search.text, prompt: Text("Rechercher"))334 .searchFocused($searchFocused)335 .searchScopes(Binding(get: { scene.search.attachmentsOnly ? 2 : scene.search.unreadOnly ? 1 : 0 }, set: { scene.search.unreadOnly = $0 == 1; scene.search.attachmentsOnly = $0 == 2 }), activation: .onSearchPresentation) {336 Text("Tous").tag(0); Text("Non lus").tag(1); Text("Pièces jointes").tag(2)337 }338 .task(id: "\(scene.search.text)|\(scene.search.unreadOnly)|\(scene.search.attachmentsOnly)") {339 try? await Task.sleep(for: .milliseconds(350))340 if !Task.isCancelled { await scene.runSearch() }341 }342 .onChange(of: scene.focusSearchToken) { _, _ in searchFocused = true }343 } else {344 content.onChange(of: scene.focusSearchToken) { _, _ in scene.openSearch(scene.search.text.isEmpty ? nil : scene.search.text) }345 }346 }347}348349/// The smart filters above the inbox: model-free insights (to reply, newsletters, unanswered) and, when AI triage is on, « Important ».350struct InsightChips: View {351 let scene: MailScene352353 private func count(_ f: InsightFilter) -> Int {354 let insights = scene.currentAccount.flatMap { scene.app.next.insights[$0] }355 switch f {356 case .needsReply: return insights?.needsReply.count ?? 0357 case .newsletters: return insights?.newsletters.count ?? 0358 case .unanswered: return insights?.unansweredSent.count ?? 0359 case .important: return scene.importantCount360 }361 }362 private func isShown(_ f: InsightFilter) -> Bool {363 if f == .important { return scene.app.next.aiEnabled(.triage) }364 return count(f) > 0 || scene.next.insightFilter == f365 }366367 private func chip(_ f: InsightFilter) -> some View {368 let on = scene.next.insightFilter == f, n = count(f)369 let fill: SPToken = on ? (f == .important ? SPColor.info : SPColor.accent) : SPColor.surface3370 let ink: SPToken = on ? SPColor.onAccent : (f == .important ? SPColor.info : SPColor.text2)371 return Button { Task { await scene.applyInsight(on ? nil : f) } } label: {372 HStack(spacing: 4) {373 Image(systemName: f.icon).imageScale(.small)374 Text(f.title)375 if n > 0 { Text("\(n)").opacity(0.75) }376 }377 .font(SPFont.caption).padding(.horizontal, 9).padding(.vertical, 4)378 .background(fill, in: Capsule())379 .foregroundStyle(ink)380 #if os(iOS)381 .frame(minHeight: 32)382 #endif383 .contentShape(Capsule())384 }385 .buttonStyle(.plain)386 .accessibilityLabel(Text(f == .important ? L("Important — classé par l’intelligence") : f.title))387 .accessibilityValue(Text("\(n)"))388 .accessibilityAddTraits(on ? .isSelected : [])389 }390391 var body: some View {392 let shown = InsightFilter.allCases.filter(isShown)393 if !shown.isEmpty {394 ScrollView(.horizontal, showsIndicators: false) {395 HStack(spacing: SPSpacing.s) { ForEach(shown) { chip($0) } }396 }397 }398 }399}400