SPB Git

Repository Public

PromptsScreen.swift 14.7 KB 313 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/PromptsScreen.swift3// Description: Prompt library: search, tag filters, favourites first, create / edit / delete, copy, and « Utiliser » which pre-fills a new conversation.4import SwiftUI5import SPChatCore67private enum PromptLimits {8    static let title = 120, body = 50_000, tags = 12, tag = 309}1011struct PromptsScreen: View {12    @Bindable var window: WindowModel13    @Environment(AppEnvironment.self) private var env14    @State private var prompts: [Prompt] = []15    @State private var loaded = false16    @State private var failed = false17    @State private var query = ""18    @State private var tag: String?19    @State private var editor: PromptDraft?20    @State private var toDelete: Prompt?21    @State private var toFill: Prompt?2223    /// Tags of the loaded prompts, most used first.24    private var tags: [String] {25        var counts: [String: Int] = [:]26        for p in prompts { for t in p.tags { counts[t, default: 0] += 1 } }27        return counts.sorted { ($1.value, $0.key) < ($0.value, $1.key) }.map(\.key)28    }2930    private var visible: [Prompt] {31        let q = query.trimmingCharacters(in: .whitespaces)32        return prompts.filter { p in33            (tag == nil || p.tags.contains(tag ?? ""))34                && (q.isEmpty || p.title.localizedStandardContains(q) || p.body.localizedStandardContains(q) || p.tags.contains { $0.localizedStandardContains(q) })35        }36        .sorted { a, b in37            if a.favorite != b.favorite { return a.favorite }38            if a.useCount != b.useCount { return a.useCount > b.useCount }39            return a.title.localizedStandardCompare(b.title) == .orderedAscending40        }41    }4243    var body: some View {44        VStack(spacing: 0) {45            toolbar46            if !tags.isEmpty { tagBar }47            Divider()48            content49        }50        .task { await load() }51        .sheet(item: $editor) { draft in52            PromptEditorSheet(draft: draft) { await load(); await env.catalog.reloadPrompts() }53        }54        .sheet(item: $toFill) { p in PromptFillSheet(prompt: p) { text in place(p, text: text) } }55        .onSync({ $0.prompts }) { Task { await load() } }56        .confirmationDialog("Supprimer le prompt « \(toDelete?.title ?? "") » ?", isPresented: Binding(get: { toDelete != nil }, set: { if !$0 { toDelete = nil } }), titleVisibility: .visible, presenting: toDelete) { p in57            Button("Supprimer", role: .destructive) { delete(p) }58            Button("Annuler", role: .cancel) {}59        } message: { _ in Text("Cette action est définitive.") }60    }6162    private var toolbar: some View {63        HStack(spacing: 10) {64            HStack(spacing: 6) {65                Image(systemName: "magnifyingglass").foregroundStyle(.secondary)66                TextField("Rechercher un prompt", text: $query).textFieldStyle(.plain).accessibilityIdentifier("prompts-search")67                if !query.isEmpty { IconButton(systemImage: "xmark.circle.fill", label: "Effacer la recherche") { query = "" } }68            }69            .padding(.horizontal, 8).padding(.vertical, 5)70            .background(.background.secondary, in: RoundedRectangle(cornerRadius: 8))71            .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.separator.opacity(0.6)))72            .frame(maxWidth: 420)73            Spacer()74            IconButton(systemImage: "arrow.clockwise", label: "Actualiser les prompts") { Task { await load() } }75            Button { editor = PromptDraft() } label: { Label("Nouveau prompt", systemImage: "plus") }76                .buttonStyle(.borderedProminent).accessibilityIdentifier("prompt-create")77        }78        .padding(.horizontal, 16).padding(.vertical, 10)79    }8081    private var tagBar: some View {82        ScrollView(.horizontal, showsIndicators: false) {83            HStack(spacing: 6) {84                TagChip(text: "Tous", selected: tag == nil) { tag = nil }85                ForEach(tags, id: \.self) { t in TagChip(text: "#" + t, selected: tag == t) { tag = tag == t ? nil : t } }86            }87            .padding(.horizontal, 16).padding(.bottom, 10)88        }89    }9091    @ViewBuilder private var content: some View {92        if !loaded { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }93        else if prompts.isEmpty {94            EmptyStateView(systemImage: failed ? "exclamationmark.triangle" : "text.quote",95                           title: failed ? "Prompts indisponibles" : "Aucun prompt",96                           message: failed ? "Vérifie ta connexion puis actualise." : "Enregistre ici les consignes que tu réutilises souvent.")97        } else if visible.isEmpty {98            EmptyStateView(systemImage: "magnifyingglass", title: "Aucun résultat", message: "Aucun prompt ne correspond à cette recherche.")99        } else {100            ScrollView {101                LazyVStack(spacing: 10) {102                    ForEach(visible) { p in103                        PromptRow(prompt: p, selectedTag: tag,104                                  onUse: { use(p) }, onCopy: { copy(p) }, onFavorite: { toggleFavorite(p) },105                                  onEdit: { editor = PromptDraft(prompt: p) }, onDelete: { toDelete = p }, onTag: { tag = $0 })106                    }107                }108                .padding(16).frame(maxWidth: 860).frame(maxWidth: .infinity)109            }110            .accessibilityIdentifier("prompts-list")111        }112    }113114    private func load() async {115        do { prompts = try await env.api.prompts(); failed = false; if let t = tag, !prompts.contains(where: { $0.tags.contains(t) }) { tag = nil } }116        catch { failed = prompts.isEmpty; env.toasts.error(error) }117        loaded = true118    }119120    private func use(_ p: Prompt) {121        // a prompt with {{variables}} is filled first; the text is then placed in the composer, never sent122        if !PromptTemplate.variables(in: p.body).isEmpty { toFill = p; return }123        place(p, text: p.body)124    }125    private func place(_ p: Prompt, text: String) {126        env.pendingComposerText = text127        if let i = prompts.firstIndex(where: { $0.id == p.id }) { prompts[i].useCount += 1 }128        Task { do { try await env.api.updatePrompt(p.id, used: true) } catch { env.toasts.error(error) } }129    }130131    private func copy(_ p: Prompt) {132        NSPasteboard.general.clearContents()133        NSPasteboard.general.setString(p.body, forType: .string)134        env.toasts.show("Prompt copié")135    }136137    private func toggleFavorite(_ p: Prompt) {138        guard let i = prompts.firstIndex(where: { $0.id == p.id }) else { return }139        let value = !p.favorite140        withAnimation(.snappy(duration: 0.2)) { prompts[i].favorite = value }141        Task {142            do { try await env.api.updatePrompt(p.id, favorite: value) }143            catch {144                if let j = prompts.firstIndex(where: { $0.id == p.id }) { prompts[j].favorite = !value }145                env.toasts.error(error)146            }147        }148    }149150    private func delete(_ p: Prompt) {151        Task {152            do { try await env.api.deletePrompt(p.id); prompts.removeAll { $0.id == p.id }; env.toasts.show("Prompt supprimé"); await load() }153            catch { env.toasts.error(error) }154        }155    }156}157158private struct TagChip: View {159    let text: String160    let selected: Bool161    let action: () -> Void162    var body: some View {163        Button(action: action) {164            Text(text).font(.caption.weight(.medium)).padding(.horizontal, 9).padding(.vertical, 4)165                .foregroundStyle(selected ? Color.white : Color.primary)166                .background(selected ? AnyShapeStyle(Palette.irisDeep) : AnyShapeStyle(.quaternary), in: Capsule())167                .contentShape(Capsule())168        }169        .buttonStyle(.plain).accessibilityAddTraits(selected ? .isSelected : [])170    }171}172173private struct PromptRow: View {174    let prompt: Prompt175    let selectedTag: String?176    let onUse: () -> Void177    let onCopy: () -> Void178    let onFavorite: () -> Void179    let onEdit: () -> Void180    let onDelete: () -> Void181    let onTag: (String) -> Void182183    var body: some View {184        VStack(alignment: .leading, spacing: 7) {185            HStack(spacing: 6) {186                if prompt.favorite { Image(systemName: "star.fill").font(.caption).foregroundStyle(DS.C.accent).accessibilityLabel("Favori") }187                Text(prompt.title).font(.headline).lineLimit(1)188                Spacer()189                IconButton(systemImage: prompt.favorite ? "star.slash" : "star", label: prompt.favorite ? "Retirer des favoris" : "Ajouter aux favoris", action: onFavorite)190                IconButton(systemImage: "doc.on.doc", label: "Copier le prompt", action: onCopy)191                IconButton(systemImage: "pencil", label: "Modifier le prompt", action: onEdit)192                IconButton(systemImage: "trash", label: "Supprimer le prompt", role: .destructive, action: onDelete)193                Button("Utiliser", action: onUse).controlSize(.small).help("Ouvre une nouvelle conversation avec ce texte dans la zone de saisie, sans l'envoyer")194            }195            Text(prompt.body).font(.callout).foregroundStyle(.secondary).lineLimit(3).frame(maxWidth: .infinity, alignment: .leading).textSelection(.enabled)196            let variables = PromptTemplate.variables(in: prompt.body)197            if !variables.isEmpty {198                HStack(spacing: 5) {199                    Image(systemName: "curlybraces").font(.caption2).foregroundStyle(DS.C.accent)200                    ForEach(variables.prefix(6), id: \.self) { v in Text(v).font(DS.F.mono(10.5)).foregroundStyle(DS.C.accent).padding(.horizontal, 5).padding(.vertical, 1.5).background(DS.C.accentSoft, in: RoundedRectangle(cornerRadius: 4)) }201                }202                .accessibilityElement(children: .combine).accessibilityLabel("Variables : " + variables.joined(separator: ", "))203            }204            HStack(spacing: 6) {205                ForEach(prompt.tags, id: \.self) { t in TagChip(text: "#" + t, selected: selectedTag == t) { onTag(t) } }206                Spacer()207                Text(usage).font(.caption2).foregroundStyle(.tertiary)208            }209        }210        .card()211        .contextMenu {212            Button("Utiliser", action: onUse)213            Button("Copier", action: onCopy)214            Button(prompt.favorite ? "Retirer des favoris" : "Ajouter aux favoris", action: onFavorite)215            Button("Modifier…", action: onEdit)216            Divider()217            Button("Supprimer…", role: .destructive, action: onDelete)218        }219    }220221    private var usage: String {222        var s = prompt.useCount == 0 ? "Jamais utilisé" : "Utilisé \(prompt.useCount) fois"223        if let d = prompt.lastUsedAt, prompt.useCount > 0 { s += " · \(Format.relative(d))" }224        return s225    }226}227228// MARK: - Editor229230private struct PromptDraft: Identifiable {231    let id = UUID()232    var promptId: String?233    var title = ""234    var body = ""235    var tags = ""236    var favorite = false237    init() {}238    init(prompt: Prompt) { promptId = prompt.id; title = prompt.title; body = prompt.body; tags = prompt.tags.joined(separator: ", "); favorite = prompt.favorite }239}240241private struct PromptEditorSheet: View {242    let onSaved: () async -> Void243    @Environment(AppEnvironment.self) private var env244    @Environment(\.dismiss) private var dismiss245    @State private var draft: PromptDraft246    @State private var busy = false247248    init(draft: PromptDraft, onSaved: @escaping () async -> Void) { _draft = State(initialValue: draft); self.onSaved = onSaved }249250    private var title: String { draft.title.trimmingCharacters(in: .whitespacesAndNewlines) }251    private var text: String { draft.body.trimmingCharacters(in: .whitespacesAndNewlines) }252    private var tags: [String] {253        var seen = Set<String>(), out: [String] = []254        for raw in draft.tags.split(whereSeparator: { $0 == "," || $0 == "\n" }) {255            var t = raw.trimmingCharacters(in: .whitespaces)256            if t.hasPrefix("#") { t.removeFirst() }257            if !t.isEmpty, seen.insert(t.lowercased()).inserted { out.append(t) }258        }259        return out260    }261    private var problem: String? {262        if title.count > PromptLimits.title { return "Titre : \(PromptLimits.title) caractères au maximum." }263        if text.count > PromptLimits.body { return "Texte : \(PromptLimits.body) caractères au maximum." }264        if tags.count > PromptLimits.tags { return "\(PromptLimits.tags) étiquettes au maximum." }265        if let long = tags.first(where: { $0.count > PromptLimits.tag }) { return "Étiquette « \(long.prefix(20))… » : \(PromptLimits.tag) caractères au maximum." }266        return nil267    }268    private var valid: Bool { !title.isEmpty && !text.isEmpty && problem == nil }269270    var body: some View {271        VStack(spacing: 0) {272            Form {273                Section(draft.promptId == nil ? "Nouveau prompt" : "Modifier le prompt") {274                    TextField("Titre", text: $draft.title)275                    TextField("Étiquettes (séparées par des virgules)", text: $draft.tags)276                    Toggle("Favori", isOn: $draft.favorite)277                }278                Section {279                    TextEditor(text: $draft.body).font(.body).frame(minHeight: 200).scrollContentBackground(.hidden).accessibilityLabel("Texte du prompt")280                } header: { Text("Texte") } footer: {281                    let vars = PromptTemplate.variables(in: draft.body)282                    Text("\(text.count) / \(PromptLimits.body) caractères · " + (vars.isEmpty ? "Écris {{nom}} pour créer une variable demandée à l'insertion." : "Variables : " + vars.joined(separator: ", ")))283                }284                if let problem { Banner(kind: .warning, text: problem) }285            }286            .formStyle(.grouped)287            Divider()288            HStack {289                if busy { ProgressView().controlSize(.small) }290                Spacer()291                Button("Annuler") { dismiss() }.keyboardShortcut(.cancelAction)292                Button(draft.promptId == nil ? "Créer" : "Enregistrer") { save() }.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).disabled(!valid || busy)293            }294            .padding(14)295        }296        .frame(width: 560, height: 540)297    }298299    private func save() {300        busy = true301        Task {302            defer { busy = false }303            do {304                if let id = draft.promptId { try await env.api.updatePrompt(id, title: title, body: text, tags: tags, favorite: draft.favorite) }305                else { _ = try await env.api.createPrompt(title: title, body: text, tags: tags, favorite: draft.favorite) }306                await onSaved()307                env.toasts.show(draft.promptId == nil ? "Prompt créé" : "Prompt enregistré")308                dismiss()309            } catch { env.toasts.error(error) }310        }311    }312}313
Files main
Menu

Theme