Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Panels/BranchesSheet.swift4// Description: Branches — the family tree of a conversation (forks, their labels, models and sizes) and the versions5// of its messages; open a branch, name it, switch a version or fork from the last message.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213struct BranchesSheet: View {14 let session: ChatSession15 @Environment(AppEnvironment.self) private var env16 @Environment(\.dismiss) private var dismiss17 @Environment(\.accessibilityReduceMotion) private var reduceMotion18 @State private var tree: ConversationTree?19 @State private var error: String?20 @State private var renaming: ConversationTree.Node?21 @State private var labelText = ""22 @State private var forking = false23 @State private var busy = false2425 var body: some View {26 VStack(spacing: 0) {27 SheetHeader(title: String(localized: "Branches"), subtitle: tree.map { $0.family.count > 1 ? String(localized: "\($0.family.count) conversations liées") : String(localized: "Cette conversation n’a pas encore de branche.") }, onClose: { dismiss() })28 ScrollView {29 VStack(alignment: .leading, spacing: 16) {30 if let t = tree {31 family(t)32 if session.messages.contains(where: { !$0.id.hasPrefix("tmp_") }) {33 Button { labelText = ""; forking = true } label: {34 Label("Nouvelle branche ici", systemImage: "arrow.triangle.branch").font(.subheadline.weight(.semibold)).foregroundStyle(Color.accentColor)35 .frame(maxWidth: .infinity, minHeight: 46).background(Color.accentSoft, in: .rect(cornerRadius: Radius.card, style: .continuous))36 }37 .buttonStyle(PressScale(scale: 0.98)).disabled(busy || session.isBusy)38 .accessibilityHint(String(localized: "Crée une conversation qui reprend le fil jusqu’au dernier message"))39 .accessibilityIdentifier("branches.fork")40 }41 if !t.variants.isEmpty { variants(t) }42 if let error { Banner(kind: .error, text: error) { self.error = nil } }43 } else if let error {44 ContentUnavailableView { Label("Branches indisponibles", systemImage: "wifi.slash") } description: { Text(error) } actions: { Button("Réessayer") { Task { await load() } } }45 } else { HStack { Spacer(); ProgressView().padding(.top, 60); Spacer() } }46 }47 .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 24)48 }49 }50 .background(Color.appBackground)51 .task { await load() }52 .refreshable { await load() }53 .alert("Nom de la branche", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {54 TextField("Nom", text: $labelText)55 Button("Annuler", role: .cancel) { renaming = nil }56 Button("Enregistrer") { if let n = renaming { rename(n, to: labelText) }; renaming = nil }57 } message: { Text("Le nom s’affiche dans l’arbre et sous le titre de la conversation.") }58 .alert("Nouvelle branche", isPresented: $forking) {59 TextField("Nom de la branche (facultatif)", text: $labelText)60 Button("Annuler", role: .cancel) {}61 Button("Créer la branche") { fork() }62 } message: { Text("Une nouvelle conversation reprend le fil jusqu’au dernier message. L’originale n’est pas modifiée.") }63 }6465 private func load() async {66 guard let id = session.conversationId else { error = String(localized: "La conversation n’a pas encore de message."); return }67 do { tree = try await env.api.tree(conversation: id); error = nil }68 catch let e { if tree == nil { error = (e as? APIError)?.message ?? String(localized: "Chargement impossible.") } }69 }7071 private func rename(_ node: ConversationTree.Node, to label: String) {72 let text = String(label.trimmingCharacters(in: .whitespacesAndNewlines).prefix(80))73 Task {74 do {75 if node.id == session.conversationId { await session.update(ConversationPatch(branchLabel: text)) }76 else { _ = try await env.api.updateConversation(node.id, ConversationPatch(branchLabel: text)); await env.conversations.refresh() }77 await load()78 } catch let e { error = (e as? APIError)?.message ?? String(localized: "Enregistrement impossible.") }79 }80 }8182 private func fork() {83 guard let last = session.messages.last(where: { !$0.id.hasPrefix("tmp_") }) else { return }84 busy = true85 Task {86 defer { busy = false }87 if let id = await session.fork(at: last, label: labelText) { env.haptics.success(); dismiss(); env.open(id) }88 else { error = session.error ?? String(localized: "Création de la branche impossible.") }89 }90 }9192 // MARK: family tree9394 private func family(_ t: ConversationTree) -> some View {95 VStack(alignment: .leading, spacing: 8) {96 Text("Arbre").font(.spMicro).tracking(0.3).textCase(.uppercase).foregroundStyle(Color.muted)97 VStack(spacing: 0) {98 ForEach(Array(t.family.enumerated()), id: \.element.id) { i, n in99 if i > 0 { Divider().padding(.leading, 14 + CGFloat(min(n.depth, 6)) * 18) }100 node(n, current: n.id == t.current)101 }102 }103 .cardSurface()104 }105 }106107 private func node(_ n: ConversationTree.Node, current: Bool) -> some View {108 HStack(spacing: 0) {109 Button {110 env.haptics.selection()111 dismiss()112 if !current { env.open(n.id) }113 } label: {114 HStack(spacing: 10) {115 if n.depth > 0 {116 Image(systemName: "arrow.turn.down.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(Color.muted)117 .padding(.leading, CGFloat(min(n.depth - 1, 5)) * 18)118 }119 ModelMark(env.catalog.model(n.modelId), size: 18)120 VStack(alignment: .leading, spacing: 2) {121 HStack(spacing: 6) {122 Text(n.branchLabel?.isEmpty == false ? n.branchLabel! : n.title).font(.subheadline.weight(current ? .semibold : .medium)).foregroundStyle(Color.textPrimary).lineLimit(1)123 if current { Text("ici").font(.spMicro).foregroundStyle(Color.accentColor).padding(.horizontal, 6).padding(.vertical, 2).background(Color.accentSoft, in: .capsule) }124 }125 Text([n.branchLabel?.isEmpty == false ? n.title : nil, String(localized: "\(n.messageCount) message(s)"), n.lastAt.map(Format.relative)].compactMap { $0 }.joined(separator: " · "))126 .font(.caption).foregroundStyle(Color.muted).lineLimit(1)127 }128 Spacer(minLength: 0)129 }130 .padding(.leading, 14).frame(minHeight: 56).contentShape(.rect)131 }132 .buttonStyle(.plain)133 .accessibilityLabel(String(localized: "\(n.branchLabel ?? n.title), niveau \(n.depth), \(n.messageCount) message(s)\(current ? ", conversation actuelle" : "")"))134 .accessibilityIdentifier("branches.node")135 Button { labelText = n.branchLabel ?? ""; renaming = n } label: { Image(systemName: "pencil").font(.system(size: 13, weight: .medium)).foregroundStyle(Color.muted).frame(width: 44, height: 44).contentShape(.rect) }136 .buttonStyle(PressScale())137 .accessibilityLabel(String(localized: "Nommer la branche \(n.branchLabel ?? n.title)"))138 .accessibilityIdentifier("branches.rename")139 }140 .background(current ? Color.accentSoft.opacity(0.6) : Color.clear)141 }142143 // MARK: message versions144145 private func variants(_ t: ConversationTree) -> some View {146 VStack(alignment: .leading, spacing: 8) {147 Text("Versions des messages").font(.spMicro).tracking(0.3).textCase(.uppercase).foregroundStyle(Color.muted)148 ForEach(t.variants) { v in149 VStack(alignment: .leading, spacing: 0) {150 Text(v.role == "user" ? String(localized: "Ton message · \(v.options.count) versions") : String(localized: "Réponse · \(v.options.count) versions"))151 .font(.spCaption).foregroundStyle(Color.textSecondary).padding(.horizontal, 14).padding(.top, 12).padding(.bottom, 4)152 ForEach(Array(v.options.enumerated()), id: \.element.id) { i, o in153 Button {154 guard !o.active, !session.isBusy else { return }155 env.haptics.selection()156 Task { await session.switchBranch(to: o.id); await load() }157 } label: {158 HStack(alignment: .top, spacing: 10) {159 Text("\(i + 1)").font(.caption.monospacedDigit().weight(.semibold)).foregroundStyle(o.active ? Color.accentColor : Color.muted)160 .frame(width: 22, height: 22).background(o.active ? Color.accentSoft : Color.surface2, in: .circle)161 VStack(alignment: .leading, spacing: 3) {162 if let m = o.model {163 let id = ModelIdentity(model: env.catalog.model(m), modelId: m, provider: nil)164 ModelChip(logo: id.logo, creatorName: id.creatorName, name: id.name, route: id.route, markSize: 13, font: .spCaption)165 }166 if !o.preview.isEmpty { Text(o.preview).font(.footnote).foregroundStyle(Color.textSecondary).lineLimit(2).multilineTextAlignment(.leading) }167 Text([o.createdAt.map(Format.relative), o.status.flatMap { $0 == "complete" ? nil : $0 }].compactMap { $0 }.joined(separator: " · ")).font(.caption2).foregroundStyle(Color.muted)168 }169 Spacer(minLength: 0)170 if o.active { Image(systemName: "checkmark").font(.footnote.weight(.bold)).foregroundStyle(Color.accentColor).accessibilityLabel(String(localized: "version affichée")) }171 }172 .padding(.horizontal, 14).padding(.vertical, 10).frame(minHeight: 44).contentShape(.rect)173 }174 .buttonStyle(.plain)175 .accessibilityAddTraits(o.active ? .isSelected : [])176 .accessibilityIdentifier("branches.variant")177 }178 }179 .cardSurface()180 }181 }182 }183}184