Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ProjectsScreen.swift3// Description: Projects workspace: list, detail editor (instructions, default model, colour, notes), conversations and files of a project, export, creation and deletion.4import SwiftUI5import UniformTypeIdentifiers6import SPChatCore78/// Colours offered by the web app (src/components/projects/project-shared.tsx).9private enum ProjectColors {10 static let all = ["#6d9cff", "#f0b35b", "#4fd1a5", "#ff6b6b", "#b48cff", "#ff9f5a", "#3cc7d6", "#e86fb3"]11 static let names = ["Bleu", "Ambre", "Vert", "Rouge", "Violet", "Orange", "Turquoise", "Rose"]12 static func name(_ hex: String) -> String { all.firstIndex(of: hex).map { names[$0] } ?? hex }13}1415private enum ProjectLimits {16 static let name = 120, description = 2000, instructions = 20_000, notes = 100_00017}1819struct ProjectsScreen: View {20 @Bindable var window: WindowModel21 @Environment(AppEnvironment.self) private var env22 @State private var projects: [Project] = []23 @State private var loaded = false24 @State private var failed = false25 @State private var selection: String?26 @State private var showCreate = false2728 var body: some View {29 HStack(spacing: 0) {30 sidebar.frame(width: 270)31 Divider()32 detail.frame(maxWidth: .infinity, maxHeight: .infinity)33 }34 .task { await load() }35 .sheet(isPresented: $showCreate) {36 ProjectCreateSheet { created in37 await load()38 selection = created.id39 }40 }41 }4243 private var sidebar: some View {44 VStack(spacing: 0) {45 HStack {46 Text("Projets").font(.headline)47 Spacer()48 IconButton(systemImage: "arrow.clockwise", label: "Actualiser les projets") { Task { await load() } }49 Button { showCreate = true } label: { Label("Nouveau", systemImage: "plus") }50 .controlSize(.small).accessibilityIdentifier("project-create").help("Créer un projet")51 }52 .padding(.horizontal, 12).padding(.vertical, 10)53 Divider()54 Group {55 if !loaded { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }56 else if projects.isEmpty {57 EmptyStateView(systemImage: failed ? "exclamationmark.triangle" : "folder",58 title: failed ? "Projets indisponibles" : "Aucun projet",59 message: failed ? "Vérifie ta connexion puis actualise." : "Un projet regroupe des conversations, des fichiers et des instructions communes.")60 } else {61 List(projects, selection: $selection) { p in ProjectRow(project: p).tag(p.id) }62 .listStyle(.sidebar)63 }64 }65 .accessibilityIdentifier("projects-list")66 }67 }6869 @ViewBuilder private var detail: some View {70 if let p = projects.first(where: { $0.id == selection }) {71 ProjectDetail(project: p, window: window, onSaved: { updated in72 if let i = projects.firstIndex(where: { $0.id == updated.id }) {73 var u = updated; u.conversationCount = projects[i].conversationCount; u.fileCount = projects[i].fileCount74 projects[i] = u75 }76 await env.catalog.reloadProjects()77 }, onDeleted: {78 selection = nil79 await load()80 }, onCountsChanged: { await load() })81 .id(p.id)82 } else if loaded && !projects.isEmpty {83 EmptyStateView(systemImage: "folder", title: "Choisis un projet", message: "Sélectionne un projet dans la liste pour voir ses conversations, ses fichiers et ses instructions.")84 } else if loaded && !failed {85 VStack(spacing: 12) {86 EmptyStateView(systemImage: "folder.badge.plus", title: "Crée ton premier projet", message: "Les instructions d'un projet s'appliquent à toutes ses conversations.")87 .frame(maxHeight: 220)88 Button("Nouveau projet") { showCreate = true }.buttonStyle(.borderedProminent)89 }90 } else { Color.clear }91 }9293 private func load() async {94 do {95 projects = try await env.api.projects(); failed = false96 if let s = selection, !projects.contains(where: { $0.id == s }) { selection = nil }97 if selection == nil { selection = projects.first?.id }98 } catch {99 failed = projects.isEmpty100 if projects.isEmpty { projects = env.catalog.projects; if selection == nil { selection = projects.first?.id } }101 env.toasts.error(error)102 }103 loaded = true104 await env.catalog.reloadProjects()105 }106}107108private struct ProjectRow: View {109 let project: Project110 var body: some View {111 HStack(alignment: .firstTextBaseline, spacing: 8) {112 Circle().fill(Palette.hex(project.color) ?? Palette.iris).frame(width: 9, height: 9).accessibilityHidden(true)113 VStack(alignment: .leading, spacing: 2) {114 Text(project.name).lineLimit(1)115 if let d = project.description, !d.isEmpty { Text(d).font(.caption).foregroundStyle(.secondary).lineLimit(2) }116 Text(counts).font(.caption2).foregroundStyle(.tertiary)117 }118 }119 .padding(.vertical, 3)120 .accessibilityElement(children: .combine)121 }122 private var counts: String {123 let c = project.conversationCount ?? 0, f = project.fileCount ?? 0124 return "\(c) conversation\(c > 1 ? "s" : "") · \(f) fichier\(f > 1 ? "s" : "")"125 }126}127128// MARK: - Detail129130private struct ProjectDetail: View {131 let project: Project132 @Bindable var window: WindowModel133 let onSaved: (Project) async -> Void134 let onDeleted: () async -> Void135 let onCountsChanged: () async -> Void136 @Environment(AppEnvironment.self) private var env137138 @State private var name: String139 @State private var description: String140 @State private var instructions: String141 @State private var notes: String142 @State private var defaultModel: String?143 @State private var color: String?144 @State private var conversations: [Conversation]?145 @State private var files: [Attachment]?146 @State private var busy = false147 @State private var confirmDelete = false148149 init(project: Project, window: WindowModel, onSaved: @escaping (Project) async -> Void, onDeleted: @escaping () async -> Void, onCountsChanged: @escaping () async -> Void) {150 self.project = project; self.window = window; self.onSaved = onSaved; self.onDeleted = onDeleted; self.onCountsChanged = onCountsChanged151 _name = State(initialValue: project.name)152 _description = State(initialValue: project.description ?? "")153 _instructions = State(initialValue: project.instructions ?? "")154 _notes = State(initialValue: project.notes ?? "")155 _defaultModel = State(initialValue: project.defaultModel)156 _color = State(initialValue: project.color)157 }158159 private var trimmedName: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }160 private var dirty: Bool {161 trimmedName != project.name || description != (project.description ?? "") || instructions != (project.instructions ?? "")162 || notes != (project.notes ?? "") || defaultModel != project.defaultModel || color != project.color163 }164 private var problem: String? {165 if trimmedName.isEmpty { return "Le nom est obligatoire." }166 if trimmedName.count > ProjectLimits.name { return "Nom : \(ProjectLimits.name) caractères au maximum." }167 if description.count > ProjectLimits.description { return "Description : \(ProjectLimits.description) caractères au maximum." }168 if instructions.count > ProjectLimits.instructions { return "Instructions : \(ProjectLimits.instructions) caractères au maximum." }169 if notes.count > ProjectLimits.notes { return "Notes : \(ProjectLimits.notes) caractères au maximum." }170 return nil171 }172173 var body: some View {174 VStack(spacing: 0) {175 header176 Divider()177 Form {178 Section("Projet") {179 TextField("Nom", text: $name)180 TextField("Description", text: $description, axis: .vertical).lineLimit(1...4)181 Picker("Modèle par défaut", selection: $defaultModel) {182 Text("Aucun (modèle habituel)").tag(String?.none)183 if let d = defaultModel, !env.catalog.selectableModels.contains(where: { $0.id == d }) {184 Text("\(env.catalog.displayName(forModel: d)) — indisponible").tag(String?.some(d))185 }186 ForEach(env.catalog.selectableModels) { Text("\($0.displayName) — \(Provider.label($0.provider))").tag(String?.some($0.id)) }187 }188 LabeledContent("Couleur") { ProjectColorPicker(color: $color) }189 }190 Section {191 TextEditor(text: $instructions).font(.body).frame(minHeight: 110).scrollContentBackground(.hidden)192 .accessibilityLabel("Instructions du projet")193 } header: { Text("Instructions") } footer: {194 Text("Ajoutées au prompt système de chaque conversation du projet. \(instructions.count) / \(ProjectLimits.instructions)")195 }196 Section {197 TextEditor(text: $notes).font(.body).frame(minHeight: 80).scrollContentBackground(.hidden)198 .accessibilityLabel("Notes du projet")199 } header: { Text("Notes") } footer: { Text("Notes personnelles : elles ne sont pas envoyées aux modèles.") }200 if let problem { Banner(kind: .warning, text: problem) }201 Section("Conversations") { conversationsList }202 Section {203 filesList204 } header: { Text("Fichiers") } footer: { Text("Les fichiers du projet se gèrent dans la section Fichiers.") }205 }206 .formStyle(.grouped)207 }208 .task { await loadContent() }209 .confirmationDialog("Supprimer le projet « \(project.name) » ?", isPresented: $confirmDelete, titleVisibility: .visible) {210 Button("Supprimer le projet", role: .destructive) { delete() }211 Button("Annuler", role: .cancel) {}212 } message: {213 Text("Les fichiers et les souvenirs du projet sont supprimés définitivement. Ses conversations sont conservées, détachées du projet.")214 }215 }216217 private var header: some View {218 HStack(spacing: 10) {219 Circle().fill(Palette.hex(color) ?? Palette.iris).frame(width: 12, height: 12).accessibilityHidden(true)220 Text(project.name).font(.title3.weight(.semibold)).lineLimit(1)221 if busy { ProgressView().controlSize(.small) }222 Spacer()223 Button { newConversation() } label: { Label("Nouvelle conversation dans ce projet", systemImage: "square.and.pencil") }.disabled(busy)224 Menu {225 Button("Markdown (.md)") { export("md") }226 Button("JSON (.json)") { export("json") }227 } label: { Label("Exporter", systemImage: "square.and.arrow.up") }228 .fixedSize().disabled(busy)229 IconButton(systemImage: "trash", label: "Supprimer le projet", role: .destructive) { confirmDelete = true }230 Button("Enregistrer") { save() }.buttonStyle(.borderedProminent).keyboardShortcut("s", modifiers: .command)231 .disabled(!dirty || problem != nil || busy)232 }233 .padding(.horizontal, 16).padding(.vertical, 10)234 }235236 @ViewBuilder private var conversationsList: some View {237 if let conversations {238 if conversations.isEmpty { Text("Aucune conversation dans ce projet.").foregroundStyle(.secondary) }239 ForEach(conversations) { c in240 Button { window.open(c.id) } label: {241 HStack {242 Image(systemName: c.archivedAt == nil ? "bubble.left" : "archivebox").foregroundStyle(.secondary)243 Text(c.title.isEmpty ? "Sans titre" : c.title).lineLimit(1)244 Spacer()245 Text("\(c.messageCount) message\(c.messageCount > 1 ? "s" : "") · \(Format.relative(c.sortDate))").font(.caption).foregroundStyle(.secondary)246 Image(systemName: "chevron.right").font(.caption).foregroundStyle(.tertiary)247 }248 .contentShape(Rectangle())249 }250 .buttonStyle(.plain).help("Ouvrir la conversation")251 }252 } else { ProgressView().controlSize(.small) }253 }254255 @ViewBuilder private var filesList: some View {256 if let files {257 if files.isEmpty { Text("Aucun fichier dans ce projet.").foregroundStyle(.secondary) }258 ForEach(files) { f in259 HStack {260 Image(systemName: f.mime.hasPrefix("image/") ? "photo" : f.mime.hasPrefix("audio/") ? "waveform" : "doc.text").foregroundStyle(.secondary)261 Text(f.filename).lineLimit(1).truncationMode(.middle)262 Spacer()263 Text(Format.bytes(f.sizeBytes)).font(.caption.monospacedDigit()).foregroundStyle(.secondary)264 indexPill(f)265 }266 .accessibilityElement(children: .combine)267 }268 } else { ProgressView().controlSize(.small) }269 }270271 private func indexPill(_ f: Attachment) -> StatusPill {272 switch f.indexStatus {273 case "indexed": StatusPill(text: (f.chunkCount ?? 0) > 0 ? "indexé · \(f.chunkCount ?? 0) passages" : "indexé", color: Palette.success, systemImage: "checkmark.circle")274 case "pending": StatusPill(text: "indexation…", color: Palette.iris, systemImage: "clock")275 case "failed": StatusPill(text: "échec d'indexation", color: Palette.danger, systemImage: "exclamationmark.triangle")276 default: StatusPill(text: "non indexé", color: .secondary, systemImage: "minus.circle")277 }278 }279280 private func loadContent() async {281 do { conversations = try await env.api.conversations(projectId: .some(project.id)) } catch { conversations = []; env.toasts.error(error) }282 do { files = try await env.api.attachments(projectId: project.id).files } catch { files = []; env.toasts.error(error) }283 }284285 private func save() {286 guard problem == nil, !busy else { return }287 busy = true288 Task {289 defer { busy = false }290 do {291 func text(_ s: String) -> JSONValue { s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? .null : .string(s) }292 let updated = try await env.api.updateProject(project.id, fields: [293 "name": .string(trimmedName), "description": text(description), "instructions": text(instructions), "notes": text(notes),294 "defaultModel": defaultModel.map(JSONValue.string) ?? .null, "color": color.map(JSONValue.string) ?? .null,295 ])296 name = updated.name; description = updated.description ?? ""; instructions = updated.instructions ?? ""; notes = updated.notes ?? ""297 defaultModel = updated.defaultModel; color = updated.color298 await onSaved(updated)299 env.toasts.show("Projet enregistré")300 } catch { env.toasts.error(error) }301 }302 }303304 private func newConversation() {305 guard !busy else { return }306 busy = true307 Task {308 defer { busy = false }309 do {310 let c = try await env.api.createConversation(modelId: project.defaultModel, projectId: project.id)311 env.conversations.upsert(c)312 await env.conversations.refreshQuietly()313 await env.catalog.reloadProjects()314 window.open(c.id)315 } catch { env.toasts.error(error) }316 }317 }318319 private func export(_ format: String) {320 guard !busy else { return }321 busy = true322 Task {323 defer { busy = false }324 do {325 let file = try await env.api.exportProject(project.id, format: format)326 let type: UTType = format == "json" ? .json : (UTType(filenameExtension: "md") ?? .plainText)327 SavePanel.save(file.data, name: file.filename ?? "Projet-\(project.name).\(format)", type: type, env: env)328 } catch { env.toasts.error(error) }329 }330 }331332 private func delete() {333 guard !busy else { return }334 busy = true335 Task {336 do {337 try await env.api.deleteProject(project.id)338 env.toasts.show("Projet supprimé")339 await env.conversations.refreshQuietly()340 await onDeleted()341 } catch { busy = false; env.toasts.error(error) }342 }343 }344}345346private struct ProjectColorPicker: View {347 @Binding var color: String?348 var body: some View {349 HStack(spacing: 7) {350 Button { color = nil } label: {351 Image(systemName: "circle.slash").foregroundStyle(color == nil ? Color.primary : Color.secondary).frame(width: 20, height: 20)352 }353 .buttonStyle(.plain).help("Aucune couleur").accessibilityLabel("Aucune couleur").accessibilityAddTraits(color == nil ? .isSelected : [])354 ForEach(ProjectColors.all, id: \.self) { hex in355 Button { color = hex } label: {356 Circle().fill(Palette.hex(hex) ?? Palette.iris).frame(width: 18, height: 18)357 .overlay(Circle().strokeBorder(Color.primary, lineWidth: color == hex ? 2 : 0).padding(-3))358 .frame(width: 24, height: 24)359 }360 .buttonStyle(.plain).help(ProjectColors.name(hex)).accessibilityLabel("Couleur \(ProjectColors.name(hex))").accessibilityAddTraits(color == hex ? .isSelected : [])361 }362 }363 }364}365366// MARK: - Creation367368private struct ProjectCreateSheet: View {369 let onCreated: (Project) async -> Void370 @Environment(AppEnvironment.self) private var env371 @Environment(\.dismiss) private var dismiss372 @State private var name = ""373 @State private var description = ""374 @State private var instructions = ""375 @State private var defaultModel: String?376 @State private var color: String? = ProjectColors.all[0]377 @State private var busy = false378379 private var trimmedName: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }380 private var valid: Bool {381 !trimmedName.isEmpty && trimmedName.count <= ProjectLimits.name && description.count <= ProjectLimits.description && instructions.count <= ProjectLimits.instructions382 }383384 var body: some View {385 VStack(spacing: 0) {386 Form {387 Section("Nouveau projet") {388 TextField("Nom", text: $name)389 TextField("Description (facultative)", text: $description, axis: .vertical).lineLimit(1...3)390 Picker("Modèle par défaut", selection: $defaultModel) {391 Text("Aucun (modèle habituel)").tag(String?.none)392 ForEach(env.catalog.selectableModels) { Text("\($0.displayName) — \(Provider.label($0.provider))").tag(String?.some($0.id)) }393 }394 LabeledContent("Couleur") { ProjectColorPicker(color: $color) }395 }396 Section {397 TextEditor(text: $instructions).font(.body).frame(minHeight: 100).scrollContentBackground(.hidden)398 .accessibilityLabel("Instructions du projet")399 } header: { Text("Instructions (facultatives)") } footer: { Text("Ajoutées au prompt système de chaque conversation du projet.") }400 }401 .formStyle(.grouped)402 Divider()403 HStack {404 if busy { ProgressView().controlSize(.small) }405 Spacer()406 Button("Annuler") { dismiss() }.keyboardShortcut(.cancelAction)407 Button("Créer") { create() }.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).disabled(!valid || busy)408 }409 .padding(14)410 }411 .frame(width: 520, height: 480)412 }413414 private func create() {415 busy = true416 Task {417 defer { busy = false }418 do {419 let p = try await env.api.createProject(name: trimmedName, description: description.trimmingCharacters(in: .whitespacesAndNewlines),420 instructions: instructions.trimmingCharacters(in: .whitespacesAndNewlines), defaultModel: defaultModel, color: color)421 await env.catalog.reloadProjects()422 await onCreated(p)423 env.toasts.show("Projet créé")424 dismiss()425 } catch { env.toasts.error(error) }426 }427 }428}429