Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Components/ConversationList.swift4// Description: Sidebar / list of conversations: sections by recency, filters, title search, swipe and context actions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftUI1112struct ConversationList: View {13 /// Called after the user picked something (the compact layout then shows the detail column).14 let onOpen: () -> Void15 @Environment(AppEnvironment.self) private var env16 @State private var query = ""17 @State private var projectId: String?18 @State private var renaming: Conversation?19 @State private var renameText = ""20 @State private var deleting: Conversation?21 @State private var showNewProject = false22 @State private var newProjectName = ""2324 var body: some View {25 @Bindable var prefs = env.preferences26 let store = env.conversations27 let items = store.conversations(filter: prefs.listFilter, projectId: projectId, query: query)28 List(selection: Binding(get: { env.router.current?.conversationId }, set: { id in if let id { env.open(id); onOpen() } })) {29 if query.isEmpty { spaces.listRowInsets(EdgeInsets()).listRowBackground(Color.clear).listRowSeparator(.hidden).selectionDisabled() }30 if !env.network.isOnline || store.isShowingCache {31 Label(env.network.isOnline ? "Serveur injoignable : copie locale" : "Hors ligne : copie locale", systemImage: "wifi.slash")32 .font(.footnote).foregroundStyle(Color.muted).listRowBackground(Color.clear).selectionDisabled()33 }34 if env.outboxCount > 0 {35 Label("\(env.outboxCount) message(s) en attente d’envoi", systemImage: "clock.arrow.circlepath")36 .font(.footnote).foregroundStyle(Color.warning).listRowBackground(Color.clear).selectionDisabled()37 }38 ForEach(Conversation.Bucket.allCases, id: \.self) { bucket in39 let rows = prefs.listFilter == .archived ? (bucket == .today ? items : []) : items.filter { $0.bucket() == bucket }40 if !rows.isEmpty {41 Section(prefs.listFilter == .archived ? String(localized: "Archives") : Self.title(bucket)) {42 ForEach(rows) { c in row(c).tag(c.id) }43 }44 }45 }46 }47 .listStyle(.sidebar)48 .overlay {49 if !store.hasLoaded { ProgressView() }50 else if items.isEmpty {51 if !query.isEmpty { ContentUnavailableView.search(text: query) }52 else if let e = store.error { ContentUnavailableView { Label("Liste indisponible", systemImage: "exclamationmark.triangle") } description: { Text(e) } actions: { Button("Réessayer") { Task { await store.refresh() } } } }53 else { ContentUnavailableView { Label(Self.emptyTitle(prefs.listFilter), systemImage: "bubble.left.and.bubble.right") } description: { Text("Les conversations de ton compte apparaissent ici, sur tous tes appareils.") } }54 }55 }56 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .automatic), prompt: Text("Filtrer par titre"))57 .refreshable { await env.synchronize() }58 .navigationTitle("SP Chat")59 .toolbarTitleDisplayMode(.large) // the sidebar toolbar holds four buttons: the title sits below it, never truncated60 .toolbar {61 ToolbarItem(placement: .topBarLeading) {62 Button { env.router.sheet = .settings } label: { Image(systemName: "gearshape") }63 .accessibilityLabel(String(localized: "Réglages")).accessibilityIdentifier("list.settings")64 }65 ToolbarItemGroup(placement: .topBarTrailing) {66 Menu {67 Picker("Afficher", selection: $prefs.listFilter) {68 Label("Toutes", systemImage: "tray.full").tag(ListFilter.all)69 Label("Favoris", systemImage: "star").tag(ListFilter.favorites)70 Label("Épinglées", systemImage: "pin").tag(ListFilter.pinned)71 Label("Archives", systemImage: "archivebox").tag(ListFilter.archived)72 }73 Picker("Projet", selection: $projectId) {74 Text("Tous les projets").tag(String?.none)75 ForEach(env.catalog.projects) { p in Text(p.name).tag(String?.some(p.id)) }76 }77 Button { showNewProject = true } label: { Label("Nouveau projet", systemImage: "folder.badge.plus") }78 } label: { Image(systemName: prefs.listFilter == .all && projectId == nil ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") }79 .accessibilityLabel(String(localized: "Filtrer les conversations"))80 Button { env.router.sheet = .search } label: { Image(systemName: "magnifyingglass") }81 .accessibilityLabel(String(localized: "Rechercher dans les messages")).accessibilityIdentifier("list.search")82 Button { env.startNewConversation(projectId: projectId); onOpen() } label: { Image(systemName: "square.and.pencil") }83 .accessibilityLabel(String(localized: "Nouvelle conversation")).accessibilityIdentifier("list.new")84 }85 }86 .alert("Renommer", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {87 TextField("Titre", text: $renameText)88 Button("Annuler", role: .cancel) { renaming = nil }89 Button("Renommer") { if let c = renaming { let t = renameText.trimmingCharacters(in: .whitespacesAndNewlines); if !t.isEmpty { Task { await store.rename(c, to: String(t.prefix(200))) } } }; renaming = nil }90 }91 .alert("Nouveau projet", isPresented: $showNewProject) {92 TextField("Nom", text: $newProjectName)93 Button("Annuler", role: .cancel) { newProjectName = "" }94 Button("Créer") { let n = newProjectName.trimmingCharacters(in: .whitespacesAndNewlines); newProjectName = ""; if !n.isEmpty { Task { if let p = await env.catalog.createProject(name: String(n.prefix(120))) { projectId = p.id } } } }95 }96 .confirmationDialog("Supprimer « \(deleting?.title ?? "") » ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {97 Button("Supprimer", role: .destructive) { if let c = deleting { Task { await store.delete(c) } }; deleting = nil }98 } message: { Text("Ses messages et ses fichiers seront supprimés du serveur, sur tous tes appareils.") }99 }100101 /// Shortcuts to the spaces of the app, kept out of the toolbar so « rechercher » and « nouvelle conversation » stay visible.102 private var spaces: some View {103 let items: [(String, String, String, () -> Void)] = [104 ("explorer", String(localized: "Modèles"), "square.grid.2x2", { env.router.sheet = .explorer }),105 ("arena", String(localized: "Arène"), "square.split.2x1", { env.router.arenaSeed = ArenaSeed(projectId: projectId); env.router.sheet = .arena }),106 ("constellation", String(localized: "Constellation"), "point.3.connected.trianglepath.dotted", { env.router.sheet = .constellation }),107 ("research", String(localized: "Recherche approfondie"), "doc.text.magnifyingglass", { env.router.sheet = .research }),108 ("images", String(localized: "Images"), "photo.on.rectangle.angled", { env.router.sheet = .images }),109 ("projects", String(localized: "Projets"), "folder", { env.router.sheet = .projects }),110 ("prompts", String(localized: "Prompts"), "text.book.closed", { env.router.sheet = .prompts }),111 ]112 return ScrollView(.horizontal, showsIndicators: false) {113 HStack(spacing: 8) {114 ForEach(items, id: \.0) { item in115 Button { env.haptics.selection(); item.3() } label: { ChipLabel(text: item.1, systemImage: item.2) }116 .buttonStyle(PressScale())117 .accessibilityIdentifier("list.space.\(item.0)")118 }119 }120 .padding(.horizontal, 16).padding(.vertical, 6)121 }122 }123124 private func row(_ c: Conversation) -> some View {125 let store = env.conversations126 let offlineUnavailable = !env.network.isOnline && !store.cachedDetailIDs.contains(c.id)127 return VStack(alignment: .leading, spacing: 3) {128 HStack(spacing: 6) {129 if c.streaming { Circle().fill(Color.accentColor).frame(width: 7, height: 7).accessibilityLabel(String(localized: "réponse en cours")) }130 Text(c.title).font(.body).lineLimit(1)131 Spacer(minLength: 0)132 if c.favorite { Image(systemName: "star.fill").font(.caption2).foregroundStyle(Color.orange) }133 if c.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Color.muted) }134 }135 HStack(spacing: 6) {136 if let m = env.catalog.model(c.modelId) { ModelMark(m, size: 12).opacity(0.8) }137 Text(Format.relative(c.sortDate))138 if c.parentId != nil { Image(systemName: "arrow.triangle.branch").font(.system(size: 9, weight: .semibold)).accessibilityLabel(String(localized: "branche")) }139 if let p = c.projectName { Text("· \(p)").lineLimit(1) }140 if c.hasDraft { Text("· brouillon").foregroundStyle(Color.accentColor) }141 if offlineUnavailable { Image(systemName: "icloud.slash").accessibilityLabel(String(localized: "Non disponible hors ligne")) }142 }143 .font(.caption).foregroundStyle(Color.muted)144 }145 .opacity(offlineUnavailable ? 0.5 : 1)146 .accessibilityElement(children: .combine)147 .accessibilityIdentifier("conversation.row")148 .swipeActions(edge: .trailing, allowsFullSwipe: false) {149 Button(role: .destructive) { deleting = c } label: { Label("Supprimer", systemImage: "trash") }150 Button { Task { await store.setArchived(c, !c.isArchived) } } label: { Label(c.isArchived ? "Désarchiver" : "Archiver", systemImage: "archivebox") }.tint(.indigo)151 }152 .swipeActions(edge: .leading) {153 Button { Task { await store.setPinned(c, !c.pinned) } } label: { Label(c.pinned ? "Désépingler" : "Épingler", systemImage: c.pinned ? "pin.slash" : "pin") }.tint(.orange)154 }155 .contextMenu {156 Button { renameText = c.title; renaming = c } label: { Label("Renommer", systemImage: "pencil") }157 Button { Task { await store.setPinned(c, !c.pinned) } } label: { Label(c.pinned ? "Désépingler" : "Épingler", systemImage: c.pinned ? "pin.slash" : "pin") }158 Button { Task { await store.setFavorite(c, !c.favorite) } } label: { Label(c.favorite ? "Retirer des favoris" : "Ajouter aux favoris", systemImage: c.favorite ? "star.slash" : "star") }159 Menu {160 Button("Aucun projet") { Task { await store.move(c, toProject: nil) } }161 ForEach(env.catalog.projects) { p in Button(p.name) { Task { await store.move(c, toProject: p.id) } } }162 } label: { Label("Déplacer vers un projet", systemImage: "folder") }163 Button { Task { await store.setArchived(c, !c.isArchived) } } label: { Label(c.isArchived ? "Désarchiver" : "Archiver", systemImage: "archivebox") }164 Divider()165 Button(role: .destructive) { deleting = c } label: { Label("Supprimer", systemImage: "trash") }166 }167 }168169 static func title(_ b: Conversation.Bucket) -> String {170 switch b {171 case .pinned: String(localized: "Épinglées"); case .today: String(localized: "Aujourd’hui"); case .yesterday: String(localized: "Hier")172 case .week: String(localized: "7 derniers jours"); case .month: String(localized: "30 derniers jours"); case .older: String(localized: "Plus ancien")173 }174 }175 static func emptyTitle(_ f: ListFilter) -> String {176 switch f { case .all: String(localized: "Aucune conversation"); case .favorites: String(localized: "Aucun favori"); case .pinned: String(localized: "Rien d’épinglé"); case .archived: String(localized: "Aucune archive") }177 }178}179