Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Chat/ConversationSidebar.swift3// Description: Conversation list with folders, favorites, tags, archive and full-text search across every message.4import SwiftUI5import LocalChatConversations6import LocalChatCore78public struct ConversationSidebar: View {9 @Environment(AppModel.self) private var app10 @Binding var selection: UUID?11 @State private var query = ""12 @State private var hits: [SearchHit] = []13 @State private var scope: Scope = .all14 @State private var renaming: Conversation?15 @State private var newFolderName = ""16 @State private var addingFolder = false1718 enum Scope: Hashable { case all, favorites, archived, folder(UUID), tag(String) }1920 public init(selection: Binding<UUID?>) { _selection = selection }2122 public var body: some View {23 VStack(spacing: 0) {24 HStack(spacing: 8) {25 HStack(spacing: 6) {26 Image(systemName: "magnifyingglass").foregroundStyle(DS.C.muted).font(.system(size: 12))27 TextField("Search all messages", text: $query).textFieldStyle(.plain).font(DS.F.callout).accessibilityIdentifier("conversation-search")28 if !query.isEmpty { Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(DS.C.muted) }.buttonStyle(.plain).accessibilityLabel("Clear search") }29 }30 .padding(.horizontal, 9).padding(.vertical, 7).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))31 Button { newChat() } label: { Image(systemName: "square.and.pencil").font(.system(size: 15, weight: .medium)) }32 .buttonStyle(.plain).foregroundStyle(DS.C.accent).help("New chat").accessibilityLabel("New chat").accessibilityIdentifier("new-chat")33 .keyboardShortcut("n", modifiers: .command)34 }35 .padding(.horizontal, 12).padding(.vertical, 10)36 scopeBar37 if !query.trimmingCharacters(in: .whitespaces).isEmpty { searchResults } else { conversationList }38 }39 .task(id: query) {40 let q = query.trimmingCharacters(in: .whitespaces)41 guard !q.isEmpty else { hits = []; return }42 try? await Task.sleep(for: .milliseconds(180))43 guard !Task.isCancelled else { return }44 hits = (try? app.store.search(q, limit: 60, includeArchived: true)) ?? []45 }46 .alert("Rename conversation", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {47 TextField("Title", text: Binding(get: { renaming?.title ?? "" }, set: { renaming?.title = $0 }))48 Button("Save") { if let r = renaming { app.update(r) }; renaming = nil }49 Button("Cancel", role: .cancel) { renaming = nil }50 }51 .alert("New folder", isPresented: $addingFolder) {52 TextField("Name", text: $newFolderName)53 Button("Create") {54 let name = newFolderName.trimmingCharacters(in: .whitespaces)55 if !name.isEmpty { _ = try? app.store.save(ChatFolder(name: name, sortIndex: app.folders.count)); app.reloadLists() }56 newFolderName = ""57 }58 Button("Cancel", role: .cancel) { newFolderName = "" }59 }60 }6162 private func newChat() {63 var folder: UUID?64 if case .folder(let id) = scope { folder = id }65 selection = app.newConversation(folder: folder).id66 Haptics.play(.light)67 }6869 private var scopeBar: some View {70 ScrollView(.horizontal, showsIndicators: false) {71 HStack(spacing: 6) {72 chip("All", symbol: "tray.full", scope: .all)73 chip("Favorites", symbol: "star", scope: .favorites)74 ForEach(app.folders) { folder in75 chip(folder.name, symbol: folder.symbol, scope: .folder(folder.id))76 .contextMenu { Button("Delete folder", systemImage: "trash", role: .destructive) { try? app.store.delete(ChatFolder.self, id: folder.id); if scope == .folder(folder.id) { scope = .all }; app.reloadLists() } }77 }78 ForEach(app.tags.prefix(8)) { tag in chip("#\(tag.tag)", symbol: nil, scope: .tag(tag.tag)) }79 chip("Archived", symbol: "archivebox", scope: .archived)80 Button { addingFolder = true } label: { Image(systemName: "folder.badge.plus").font(.system(size: 12)) }81 .buttonStyle(.plain).foregroundStyle(DS.C.muted).padding(.horizontal, 6).accessibilityLabel("New folder")82 }83 .padding(.horizontal, 12).padding(.bottom, 8)84 }85 }8687 private func chip(_ title: String, symbol: String?, scope target: Scope) -> some View {88 Button { withAnimation(DS.M.snappy) { scope = target } } label: {89 HStack(spacing: 4) {90 if let symbol { Image(systemName: symbol).font(.system(size: 10)) }91 Text(title).font(DS.F.micro).lineLimit(1)92 }93 .foregroundStyle(scope == target ? .white : DS.C.text2)94 .padding(.horizontal, 9).padding(.vertical, 5)95 .background(scope == target ? AnyShapeStyle(DS.G.accent) : AnyShapeStyle(DS.C.surface2), in: Capsule())96 }97 .buttonStyle(.plain)98 }99100 private var filtered: [Conversation] {101 app.conversations.filter { c in102 switch scope {103 case .all: !c.isArchived104 case .favorites: c.isFavorite && !c.isArchived105 case .archived: c.isArchived106 case .folder(let id): c.folderID == id && !c.isArchived107 case .tag(let tag): c.tags.contains(tag) && !c.isArchived108 }109 }110 }111112 private var conversationList: some View {113 Group {114 if filtered.isEmpty {115 EmptyStateView(symbol: "bubble.left.and.bubble.right", title: "No conversations", message: "Start a new chat. Everything stays on this device unless you choose otherwise.") {116 Button("New chat", action: newChat).buttonStyle(.lcPrimaryCompact)117 }118 } else {119 List(selection: $selection) {120 ForEach(grouped, id: \.title) { section in121 Section(section.title) {122 ForEach(section.items) { conversation in123 ConversationRow(conversation: conversation, isGenerating: !app.snapshot.active.isEmpty && app.isGenerating(conversation.id))124 .tag(conversation.id)125 .contextMenu { rowMenu(conversation) }126 .swipeActions(edge: .trailing) {127 Button(role: .destructive) { delete(conversation) } label: { Label("Delete", systemImage: "trash") }128 Button { toggle(conversation, \.isArchived) } label: { Label(conversation.isArchived ? "Unarchive" : "Archive", systemImage: "archivebox") }129 }130 .swipeActions(edge: .leading) {131 Button { toggle(conversation, \.isFavorite) } label: { Label("Favorite", systemImage: conversation.isFavorite ? "star.slash" : "star") }.tint(DS.C.warn)132 }133 }134 }135 }136 }137 .listStyle(.sidebar).scrollContentBackground(.hidden)138 }139 }140 }141142 private var grouped: [(title: String, items: [Conversation])] {143 let calendar = Calendar.current; let now = Date()144 var buckets: [(String, [Conversation])] = [("Today", []), ("Previous 7 days", []), ("Previous 30 days", []), ("Older", [])]145 for c in filtered {146 let days = calendar.dateComponents([.day], from: calendar.startOfDay(for: c.updatedAt), to: calendar.startOfDay(for: now)).day ?? 0147 let index = days <= 0 ? 0 : days <= 7 ? 1 : days <= 30 ? 2 : 3148 buckets[index].1.append(c)149 }150 return buckets.filter { !$0.1.isEmpty }.map { (title: $0.0, items: $0.1) }151 }152153 @ViewBuilder private func rowMenu(_ c: Conversation) -> some View {154 Button("Rename…", systemImage: "pencil") { renaming = c }155 Button(c.isFavorite ? "Remove from favorites" : "Add to favorites", systemImage: "star") { toggle(c, \.isFavorite) }156 Menu("Move to folder", systemImage: "folder") {157 Button("None") { var copy = c; copy.folderID = nil; app.update(copy) }158 ForEach(app.folders) { folder in Button(folder.name) { var copy = c; copy.folderID = folder.id; app.update(copy) } }159 }160 Button("Duplicate", systemImage: "plus.square.on.square") { if let copy = try? app.store.duplicateConversation(c.id) { selection = copy.id } }161 Button(c.isArchived ? "Unarchive" : "Archive", systemImage: "archivebox") { toggle(c, \.isArchived) }162 Divider()163 Button("Delete", systemImage: "trash", role: .destructive) { delete(c) }164 }165166 private func toggle(_ c: Conversation, _ keyPath: WritableKeyPath<Conversation, Bool>) { var copy = c; copy[keyPath: keyPath].toggle(); app.update(copy) }167 private func delete(_ c: Conversation) { if selection == c.id { selection = nil }; app.deleteConversation(c.id) }168169 private var searchResults: some View {170 Group {171 if hits.isEmpty {172 EmptyStateView(symbol: "magnifyingglass", title: "No match", message: "No message or title contains “\(query)”.")173 } else {174 List {175 ForEach(hits) { hit in176 Button { selection = hit.conversationID } label: {177 VStack(alignment: .leading, spacing: 3) {178 Text(hit.conversationTitle).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(DS.C.text).lineLimit(1)179 hit.snippetRuns.reduce(Text("")) { $0 + Text($1.text).fontWeight($1.isMatch ? .bold : .regular).foregroundStyle($1.isMatch ? DS.C.accent : DS.C.text2) }180 .font(DS.F.caption).lineLimit(3)181 }182 }183 .buttonStyle(.plain)184 }185 }186 .listStyle(.sidebar).scrollContentBackground(.hidden)187 }188 }189 }190}191192struct ConversationRow: View {193 let conversation: Conversation194 let isGenerating: Bool195 var body: some View {196 HStack(spacing: 8) {197 VStack(alignment: .leading, spacing: 2) {198 Text(conversation.title).font(.system(size: 13, weight: .medium)).foregroundStyle(DS.C.text).lineLimit(1)199 HStack(spacing: 5) {200 Text(conversation.updatedAt, format: .relative(presentation: .named)).font(DS.F.micro).foregroundStyle(DS.C.muted)201 ForEach(conversation.tags.prefix(2), id: \.self) { Text("#\($0)").font(DS.F.micro).foregroundStyle(DS.C.accent) }202 }203 }204 Spacer(minLength: 0)205 if isGenerating { ProgressView().controlSize(.mini) }206 if conversation.isFavorite { Image(systemName: "star.fill").font(.system(size: 9)).foregroundStyle(DS.C.warn) }207 if conversation.agentID != nil { Image(systemName: "sparkle").font(.system(size: 9)).foregroundStyle(DS.C.accent2) }208 }209 .padding(.vertical, 2)210 .accessibilityElement(children: .combine)211 }212}213