SPB Git

Repository Public

ProjectsView.swift 15.3 KB 277 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Projects/ProjectsView.swift4//  Description: Projects of the account: list, creation and the editor (name, description, instructions applied to5//               every conversation of the project, default model, colour), the project's files, deletion.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import QuickLook12import SwiftUI1314/// The eight project colours of the web app (stored as hex strings on the server).15enum ProjectPalette {16    static let hexes = ["#6d9cff", "#f0b35b", "#4fd1a5", "#ff6b6b", "#b48cff", "#ff9f5a", "#3cc7d6", "#e86fb3"]17    static func color(_ hex: String?) -> Color? {18        guard var h = hex?.trimmingCharacters(in: .whitespaces), !h.isEmpty else { return nil }19        if h.hasPrefix("#") { h.removeFirst() }20        guard h.count == 6, let v = UInt32(h, radix: 16) else { return nil }21        return Color(red: Double((v >> 16) & 0xFF) / 255, green: Double((v >> 8) & 0xFF) / 255, blue: Double(v & 0xFF) / 255)22    }23    static func name(_ hex: String) -> String {24        switch hex.lowercased() {25        case "#6d9cff": String(localized: "Bleu"); case "#f0b35b": String(localized: "Ambre"); case "#4fd1a5": String(localized: "Jade"); case "#ff6b6b": String(localized: "Rouge")26        case "#b48cff": String(localized: "Violet"); case "#ff9f5a": String(localized: "Orange"); case "#3cc7d6": String(localized: "Turquoise"); case "#e86fb3": String(localized: "Rose")27        default: hex28        }29    }30}3132struct ProjectDot: View {33    var color: String?34    var size: CGFloat = 1235    var body: some View {36        RoundedRectangle(cornerRadius: size * 0.3, style: .continuous).fill(ProjectPalette.color(color) ?? Color.muted.opacity(0.5)).frame(width: size, height: size).accessibilityHidden(true)37    }38}3940struct ProjectsView: View {41    @Environment(AppEnvironment.self) private var env42    @Environment(\.dismiss) private var dismiss43    @State private var showNew = false44    @State private var newName = ""45    @State private var error: String?46    @State private var path: [String] = []4748    var body: some View {49        let projects = env.catalog.projects50        NavigationStack(path: $path) {51            List {52                ForEach(projects) { p in53                    NavigationLink(value: p.id) {54                        HStack(spacing: 12) {55                            ProjectDot(color: p.color, size: 14)56                            VStack(alignment: .leading, spacing: 3) {57                                Text(p.name).font(.body.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)58                                HStack(spacing: 6) {59                                    Text(p.conversationCount > 1 ? String(localized: "\(p.conversationCount) conversations") : String(localized: "\(p.conversationCount) conversation"))60                                    if p.fileCount > 0 { Text(p.fileCount > 1 ? String(localized: "· \(p.fileCount) fichiers") : String(localized: "· \(p.fileCount) fichier")) }61                                    if (p.instructions ?? "").isEmpty == false { Image(systemName: "text.badge.star").accessibilityLabel(String(localized: "instructions définies")) }62                                    if let m = env.catalog.model(p.defaultModel) { ModelMark(m, size: 12).accessibilityLabel(String(localized: "modèle par défaut : \(m.displayName)")) }63                                }64                                .font(.caption).foregroundStyle(Color.muted).lineLimit(1)65                            }66                        }67                        .frame(minHeight: 46)68                    }69                    .accessibilityIdentifier("projects.row")70                }71                if let error { Text(error).font(.footnote).foregroundStyle(Color.danger) }72            }73            .listStyle(.plain)74            .scrollContentBackground(.hidden)75            .background(Color.appBackground)76            .overlay {77                if projects.isEmpty {78                    ContentUnavailableView { Label("Aucun projet", systemImage: "folder") } description: { Text("Un projet regroupe des conversations et leur donne des instructions, un modèle par défaut et des fichiers communs.") } actions: { Button("Nouveau projet") { showNew = true } }79                }80            }81            .navigationTitle("Projets").navigationBarTitleDisplayMode(.inline)82            .navigationDestination(for: String.self) { id in ProjectEditor(projectId: id, onClose: { dismiss() }, onDeleted: { path.removeAll() }) }83            .toolbar {84                ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }85                ToolbarItem(placement: .primaryAction) { Button { showNew = true } label: { Image(systemName: "plus") }.accessibilityLabel(String(localized: "Nouveau projet")).accessibilityIdentifier("projects.new") }86            }87            .alert("Nouveau projet", isPresented: $showNew) {88                TextField("Nom", text: $newName)89                Button("Annuler", role: .cancel) { newName = "" }90                Button("Créer") {91                    let n = String(newName.trimmingCharacters(in: .whitespacesAndNewlines).prefix(120)); newName = ""92                    guard !n.isEmpty else { return }93                    Task {94                        if let p = await env.catalog.createProject(name: n) { env.haptics.success(); await env.catalog.refreshPresetsAndProjects(); path = [p.id] }95                        else { error = String(localized: "Le projet n’a pas pu être créé.") }96                    }97                }98            }99            .task { await env.catalog.refreshPresetsAndProjects() }100            .refreshable { await env.catalog.refreshPresetsAndProjects() }101        }102        .accessibilityIdentifier("projects.screen")103    }104}105106/// Editor of one project. Changes are sent as a patch of what differs; the catalogue is reloaded after each save.107struct ProjectEditor: View {108    let projectId: String109    let onClose: () -> Void110    let onDeleted: () -> Void111    @Environment(AppEnvironment.self) private var env112    @State private var original: Project?113    @State private var name = ""114    @State private var summary = ""115    @State private var instructions = ""116    @State private var defaultModel: String?117    @State private var color: String?118    @State private var files: [Attachment] = []119    @State private var memoryCount = 0120    @State private var loaded = false121    @State private var saving = false122    @State private var message: String?123    @State private var failed = false124    @State private var pickingModel = false125    @State private var confirmDelete = false126    @State private var previewURL: URL?127128    private var patch: ProjectPatch { original.map { ProjectPatch(from: $0, name: name, description: summary, instructions: instructions, defaultModel: defaultModel, color: color) } ?? ProjectPatch() }129130    var body: some View {131        Form {132            Section {133                TextField("Nom", text: $name).accessibilityIdentifier("project.name")134                TextField("Description (facultative)", text: $summary, axis: .vertical).lineLimit(1...4).accessibilityIdentifier("project.description")135            } header: { Text("Projet") }136137            Section {138                TextEditor(text: $instructions).frame(minHeight: 160).accessibilityIdentifier("project.instructions")139            } header: { Text("Instructions") } footer: {140                Text("\(instructions.count) / 20 000 — ajoutées par le serveur à chaque conversation de ce projet, quel que soit le modèle.")141                    .foregroundStyle(instructions.count > 20_000 ? Color.danger : Color.muted)142            }143144            Section {145                Button { pickingModel = true } label: {146                    HStack {147                        Text("Modèle par défaut").foregroundStyle(Color.textPrimary)148                        Spacer(minLength: 12)149                        if let id = defaultModel {150                            if let m = env.catalog.model(id) { ModelChip(model: m, markSize: 16, font: .subheadline) } else { Text(id).font(.subheadline).foregroundStyle(Color.textSecondary).lineLimit(1) }151                        } else { Text("Celui du compte").font(.subheadline).foregroundStyle(Color.muted) }152                        Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted)153                    }154                    .contentShape(.rect)155                }156                .buttonStyle(.plain)157                .accessibilityIdentifier("project.model")158                if defaultModel != nil { Button("Revenir au modèle du compte") { defaultModel = nil }.accessibilityIdentifier("project.clearModel") }159            } footer: { Text("Proposé pour les nouvelles conversations du projet ; tu peux toujours en choisir un autre dans le compositeur.") }160161            Section("Couleur") {162                ScrollView(.horizontal, showsIndicators: false) {163                    HStack(spacing: 10) {164                        swatch(nil)165                        ForEach(ProjectPalette.hexes, id: \.self) { swatch($0) }166                    }167                    .padding(.vertical, 2)168                }169            }170171            if let message { Section { Label(message, systemImage: failed ? "exclamationmark.triangle" : "checkmark.circle").font(.footnote).foregroundStyle(failed ? Color.danger : Color.success).accessibilityIdentifier("project.message") } }172173            Section {174                Button { env.startNewConversation(projectId: projectId); onClose() } label: { Label("Nouvelle conversation dans ce projet", systemImage: "square.and.pencil") }175                    .accessibilityIdentifier("project.newConversation")176                if let o = original { LabeledContent("Conversations", value: o.conversationCount.formatted()) }177                if memoryCount > 0 { LabeledContent("Souvenirs du projet", value: memoryCount.formatted()) }178            }179180            if !files.isEmpty {181                Section {182                    ForEach(files) { f in183                        Button { Task { previewURL = try? await env.files.fileURL(for: f.id, filename: f.filename) } } label: {184                            HStack(spacing: 12) {185                                Image(systemName: f.isImage ? "photo" : "doc.fill").foregroundStyle(Color.accentColor).frame(width: 24)186                                VStack(alignment: .leading, spacing: 2) {187                                    Text(f.filename).foregroundStyle(Color.textPrimary).lineLimit(1)188                                    Text([Format.bytes(f.sizeBytes), f.pageCount.map { String(localized: "\($0) pages") }, f.indexStatus == "indexed" ? String(localized: "indexé") : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Color.muted)189                                }190                            }191                            .contentShape(.rect)192                        }193                        .buttonStyle(.plain)194                    }195                } header: { Text("Fichiers du projet") } footer: { Text("Lecture seule ici : les fichiers s’ajoutent en les joignant à une conversation du projet.") }196            }197198            Section {199                Button("Supprimer le projet", role: .destructive) { confirmDelete = true }.accessibilityIdentifier("project.delete")200            } footer: { Text("Les fichiers de la bibliothèque du projet et ses souvenirs sont supprimés ; ses conversations sont conservées, sans projet.") }201        }202        .navigationTitle(original?.name ?? String(localized: "Projet")).navigationBarTitleDisplayMode(.inline)203        .toolbar {204            ToolbarItem(placement: .confirmationAction) {205                Button { Task { await save() } } label: { if saving { ProgressView() } else { Text("Enregistrer").fontWeight(.semibold) } }206                    .disabled(saving || !loaded || patch.isEmpty || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || instructions.count > 20_000)207                    .accessibilityIdentifier("project.save")208            }209        }210        .sheet(isPresented: $pickingModel) {211            ModelSheet(purpose: .pick(title: String(localized: "Modèle par défaut du projet"), current: defaultModel) { m in defaultModel = m.id }).presentationDetents([.large])212        }213        .quickLookPreview($previewURL)214        .confirmationDialog("Supprimer « \(original?.name ?? "") » ?", isPresented: $confirmDelete, titleVisibility: .visible) {215            Button("Supprimer", role: .destructive) { Task { await delete() } }216        } message: { Text("Cette action est définitive, sur tous tes appareils.") }217        .task(id: projectId) { await load() }218    }219220    private func swatch(_ hex: String?) -> some View {221        let on = color?.lowercased() == hex?.lowercased()222        return Button { env.haptics.selection(); color = hex } label: {223            ZStack {224                Circle().fill(ProjectPalette.color(hex) ?? Color.surface2).frame(width: 30, height: 30)225                if hex == nil { Image(systemName: "slash.circle").font(.system(size: 15)).foregroundStyle(Color.muted) }226                if on { Circle().strokeBorder(Color.textPrimary, lineWidth: 2).frame(width: 38, height: 38) }227            }228            .frame(width: 44, height: 44).contentShape(.rect)229        }230        .buttonStyle(PressScale())231        .accessibilityLabel(hex.map(ProjectPalette.name) ?? String(localized: "Aucune couleur"))232        .accessibilityAddTraits(on ? .isSelected : [])233    }234235    private func apply(_ p: Project) {236        original = p; name = p.name; summary = p.description ?? ""; instructions = p.instructions ?? ""; defaultModel = p.defaultModel; color = p.color237    }238239    private func load() async {240        if !loaded, let cached = env.catalog.project(projectId) { apply(cached) }241        do {242            let d = try await env.api.projectDetail(projectId)243            // the list row carries the counts; the detail row carries the fields244            var p = d.project245            if let cached = env.catalog.project(projectId) { p.conversationCount = cached.conversationCount; p.fileCount = cached.fileCount }246            if !loaded || patch.isEmpty { apply(p) }247            files = d.files; memoryCount = d.memoryCount; loaded = true248        } catch {249            loaded = original != nil250            if original == nil { failed = true; message = (error as? APIError)?.message ?? String(localized: "Projet indisponible.") }251        }252    }253254    private func save() async {255        let p = patch256        guard !p.isEmpty else { return }257        saving = true; defer { saving = false }258        do {259            var updated = try await env.api.updateProject(projectId, patch: p)260            if let o = original { updated.conversationCount = o.conversationCount; updated.fileCount = o.fileCount }261            apply(updated)262            failed = false; message = String(localized: "Enregistré sur le serveur.")263            env.haptics.success()264            await env.catalog.refreshPresetsAndProjects()265        } catch { failed = true; message = (error as? APIError)?.message ?? String(localized: "Enregistrement impossible.") }266    }267268    private func delete() async {269        do {270            try await env.api.deleteProject(projectId)271            await env.catalog.refreshPresetsAndProjects()272            await env.conversations.refresh()273            onDeleted()274        } catch { failed = true; message = (error as? APIError)?.message ?? String(localized: "Suppression impossible.") }275    }276}277
Files main
Menu

Theme