SPB Git

Repository Public

ConstellationView.swift 25.4 KB 438 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Constellation/ConstellationView.swift4//  Description: Conversation Constellation — the account's conversations as an interactive native graph (SwiftUI Canvas):5//               nodes by project, links by kind (branch, project, topic), pinch / pan / drag, tap to open. The legend6//               states, in the server's own words, what each kind of link is based on.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI1314struct ConstellationView: View {15    /// Called when a conversation is opened (the compact layout then shows the detail column).16    let onOpen: () -> Void1718    @Environment(AppEnvironment.self) private var env19    @Environment(\.dismiss) private var dismiss20    @Environment(\.accessibilityReduceMotion) private var reduceMotion21    @Environment(\.colorScheme) private var scheme22    @State private var model: ConstellationModel?23    @State private var showList = false24    @State private var legendOpen = false25    // view transform: the graph is fitted in the canvas (`fit`), then the owner zooms and pans26    @State private var fit: CGFloat = 127    @State private var zoom: CGFloat = 128    @State private var zoomStart: CGFloat?29    @State private var pan: CGSize = .zero30    @State private var panStart: CGSize?31    @State private var dragging: Int?32    @State private var dragDecided = false33    @State private var canvasAspect: Double = 1.63435    var body: some View {36        NavigationStack {37            Group {38                if let model {39                    if model.nodes.isEmpty {40                        emptyState(model)41                    } else if showList {42                        nodeList(model)43                    } else {44                        graph(model)45                    }46                } else { ProgressView() }47            }48            .frame(maxWidth: .infinity, maxHeight: .infinity)49            .onGeometryChange(for: Double.self) { g in g.size.width > 0 ? Double((g.size.height - 150) / g.size.width) : 1.6 } action: { canvasAspect = $0 }50            .background(Color.appBackground)51            .navigationTitle("Constellation").navigationBarTitleDisplayMode(.inline)52            .toolbar { toolbar }53        }54        .task {55            if model == nil { model = ConstellationModel(api: env.api) }56            await Task.yield()57            model?.aspect = canvasAspect58            await model?.load(reduceMotion: reduceMotion)59        }60        .onDisappear { model?.stop() }61    }6263    @ToolbarContentBuilder private var toolbar: some ToolbarContent {64        ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("constellation.close") }65        ToolbarItemGroup(placement: .primaryAction) {66            if let model {67                let projects = model.graph?.projects ?? []68                if !projects.isEmpty || model.projectId != nil {69                    Menu {70                        Picker("Projet", selection: Binding(get: { model.projectId }, set: { id in model.projectId = id; resetView(); Task { await model.load(reduceMotion: reduceMotion) } })) {71                            Text("Tous les projets").tag(String?.none)72                            ForEach(projects) { p in Text(p.name).tag(String?.some(p.id)) }73                            // the current filter stays selectable even if the server no longer lists the project74                            if let id = model.projectId, !projects.contains(where: { $0.id == id }) { Text(env.catalog.project(id)?.name ?? String(localized: "Projet")).tag(String?.some(id)) }75                        }76                    } label: { Image(systemName: model.projectId == nil ? "folder" : "folder.fill") }77                    .accessibilityLabel(String(localized: "Filtrer par projet"))78                    .accessibilityIdentifier("constellation.project")79                }80                Button { withAnimation(Motion.fade) { showList.toggle() } } label: { Image(systemName: showList ? "point.3.connected.trianglepath.dotted" : "list.bullet") }81                    .accessibilityLabel(showList ? String(localized: "Afficher le graphe") : String(localized: "Afficher la liste"))82                    .accessibilityIdentifier("constellation.listToggle")83            }84        }85    }8687    private func resetView() { zoom = 1; pan = .zero }8889    // MARK: graph9091    private func graph(_ model: ConstellationModel) -> some View {92        GeometryReader { geo in93            let size = geo.size94            Canvas { context, canvasSize in95                draw(&context, size: canvasSize, model: model)96            }97            .contentShape(.rect)98            .gesture(dragGesture(model, size: size))99            .simultaneousGesture(MagnifyGesture()100                .onChanged { v in101                    if zoomStart == nil { zoomStart = zoom }102                    zoom = min(max((zoomStart ?? 1) * v.magnification, 0.4), 4)103                }104                .onEnded { _ in zoomStart = nil })105            .simultaneousGesture(SpatialTapGesture().onEnded { v in106                let hit = hitTest(v.location, size: size, model: model)107                env.haptics.selection()108                withAnimation(Motion.snappy(reduceMotion)) { model.selection = hit.map { model.nodes[$0].id } }109            })110            .onChange(of: model.positions, initial: true) { refit(model, size: size) }111            .onChange(of: size) { refit(model, size: size, force: true) }112            .accessibilityElement(children: .contain)113            .accessibilityLabel(String(localized: "Graphe de \(model.nodes.count) conversation(s)"))114            .accessibilityChildren {115                ForEach(model.nodes) { n in116                    Button(n.title) { open(n) }117                        .accessibilityHint(String(localized: "\(n.messages) message(s)\(n.projectName.map { ", projet \($0)" } ?? ""). Ouvre la conversation."))118                }119            }120            .accessibilityIdentifier("constellation.canvas")121        }122        .overlay(alignment: .top) { legend(model).padding(.horizontal, 12).padding(.top, 8) }123        .overlay(alignment: .bottom) {124            VStack(spacing: 8) {125                if model.selectedNode == nil { hint(model) }126                if let n = model.selectedNode { card(n, model).transition(.move(edge: .bottom).combined(with: .opacity)) }127            }128            .padding(.horizontal, 12).padding(.bottom, 10)129        }130        .animation(Motion.smooth(reduceMotion), value: model.selection)131    }132133    /// Fits the layout in the canvas while it settles; frozen while the owner drags a node so nothing slides under the finger.134    private func refit(_ model: ConstellationModel, size: CGSize, force: Bool = false) {135        guard dragging == nil, model.isSettling || force || fit == 1, !model.positions.isEmpty, size.width > 0 else { return }136        let extentX = model.positions.reduce(CGFloat(40)) { max($0, abs($1.x)) } + 44137        let extentY = model.positions.reduce(CGFloat(40)) { max($0, abs($1.y)) } + 40138        let target = min(max(min(size.width / (2 * extentX), (size.height - 170) / (2 * extentY)), 0.25), 1.6)139        if abs(target - fit) > 0.002 { fit = target }140    }141142    private var scale: CGFloat { fit * zoom }143    private func project(_ p: CGPoint, size: CGSize) -> CGPoint {144        CGPoint(x: size.width / 2 + pan.width + p.x * scale, y: size.height / 2 + pan.height + p.y * scale)145    }146    private func unproject(_ p: CGPoint, size: CGSize) -> CGPoint {147        CGPoint(x: (p.x - size.width / 2 - pan.width) / scale, y: (p.y - size.height / 2 - pan.height) / scale)148    }149    private func radius(_ n: Constellation.Node) -> CGFloat {150        let base = 6 + 2.4 * CGFloat(Double(max(n.messages, 1)).squareRoot())151        return min(base, 22) * min(max(scale, 0.75), 1.5)152    }153154    /// Nearest node under a point (with a 44 pt target around small nodes).155    private func hitTest(_ location: CGPoint, size: CGSize, model: ConstellationModel) -> Int? {156        var best: (Int, CGFloat)?157        for (i, n) in model.nodes.enumerated() where i < model.positions.count {158            let c = project(model.positions[i], size: size)159            let d = hypot(c.x - location.x, c.y - location.y)160            if d <= max(radius(n) + 8, 22), d < (best?.1 ?? .infinity) { best = (i, d) }161        }162        return best?.0163    }164165    private func dragGesture(_ model: ConstellationModel, size: CGSize) -> some Gesture {166        DragGesture(minimumDistance: 4)167            .onChanged { v in168                if !dragDecided {169                    dragDecided = true170                    dragging = hitTest(v.startLocation, size: size, model: model)171                    if dragging != nil { env.haptics.soften() } else { panStart = pan }172                }173                if let i = dragging { model.drag(i, to: unproject(v.location, size: size)) }174                else if let start = panStart { pan = CGSize(width: start.width + v.translation.width, height: start.height + v.translation.height) }175            }176            .onEnded { _ in177                if let i = dragging { model.endDrag(i, reduceMotion: reduceMotion) }178                dragging = nil; panStart = nil; dragDecided = false179            }180    }181182    private func draw(_ context: inout GraphicsContext, size: CGSize, model: ConstellationModel) {183        let nodes = model.nodes, positions = model.positions184        guard positions.count == nodes.count, let graph = model.graph else { return }185        let index = Dictionary(nodes.enumerated().map { ($0.element.id, $0.offset) }, uniquingKeysWith: { a, _ in a })186        let selected = model.selection187        let neighbours: Set<String> = selected.map { s in Set(graph.links.filter { $0.source == s || $0.target == s }.flatMap { [$0.source, $0.target] }) } ?? []188189        for l in graph.links {190            guard let a = index[l.source], let b = index[l.target] else { continue }191            var path = Path(); path.move(to: project(positions[a], size: size)); path.addLine(to: project(positions[b], size: size))192            let touches = selected != nil && (l.source == selected || l.target == selected)193            let dim: Double = selected == nil || touches ? 1 : 0.35194            let color = touches ? Color.accentColor : Color.textSecondary195            switch l.kind {196            case "branch": context.stroke(path, with: .color(color.opacity(0.85 * dim)), style: StrokeStyle(lineWidth: 1.6, lineCap: .round))197            case "project": context.stroke(path, with: .color(color.opacity(0.6 * dim)), style: StrokeStyle(lineWidth: 1.1, lineCap: .round, dash: [5, 4]))198            default: context.stroke(path, with: .color(color.opacity((0.14 + 0.5 * min(max(l.weight, 0), 1)) * dim)), style: StrokeStyle(lineWidth: 0.8))199            }200        }201202        // labels never overlap: the selection first, then the biggest nodes; a label that would collide is left out203        var labelled: [CGRect] = []204        var labels: [(GraphicsContext.ResolvedText, CGPoint, CGRect)] = []205        for (i, n) in nodes.enumerated().sorted(by: { a, b in (a.element.id == selected ? 1 : 0, a.element.messages) > (b.element.id == selected ? 1 : 0, b.element.messages) }) {206            let c = project(positions[i], size: size), r = radius(n)207            guard c.x > 0, c.y > 0, c.x < size.width, c.y < size.height else { continue }208            let isSelected = n.id == selected209            let dim: Double = selected == nil || isSelected || neighbours.contains(n.id) ? 1 : 0.4210            let title = n.title.count > 22 ? String(n.title.prefix(21)) + "…" : n.title211            let resolved = context.resolve(Text(title).font(.system(size: 10.5, weight: isSelected ? .semibold : .medium)).foregroundStyle(isSelected ? Color.textPrimary : Color.textSecondary.opacity(dim)))212            let m = resolved.measure(in: CGSize(width: 220, height: 40))213            let at = CGPoint(x: min(max(c.x, m.width / 2 + 4), size.width - m.width / 2 - 4), y: c.y + r + 9)214            let rect = CGRect(x: at.x - m.width / 2 - 3, y: at.y - m.height / 2 - 1, width: m.width + 6, height: m.height + 2)215            if isSelected || !labelled.contains(where: { $0.intersects(rect) }) { labelled.append(rect); labels.append((resolved, at, rect)) }216        }217        for (i, n) in nodes.enumerated() {218            let c = project(positions[i], size: size), r = radius(n)219            guard c.x > -60, c.y > -60, c.x < size.width + 60, c.y < size.height + 60 else { continue }220            let isSelected = n.id == selected221            let dim: Double = selected == nil || isSelected || neighbours.contains(n.id) ? 1 : 0.4222            let rect = CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r)223            if isSelected {224                // the one light of the system: an iris halo around the selection225                context.fill(Path(ellipseIn: rect.insetBy(dx: -7, dy: -7)), with: .color(Color.accentColor.opacity(0.22)))226                context.fill(Path(ellipseIn: rect), with: .color(.accentColor))227            } else {228                let fill = Self.projectColor(n.projectColor, id: n.projectId) ?? Color.muted229                // opaque disc first (links never show through a node), then the node colour, dimmed when not in focus230                context.fill(Path(ellipseIn: rect.insetBy(dx: -1.5, dy: -1.5)), with: .color(Color.appBackground))231                context.fill(Path(ellipseIn: rect), with: .color(fill.opacity(dim)))232            }233            if n.pinned || n.favorite {234                context.stroke(Path(ellipseIn: rect.insetBy(dx: -3, dy: -3)), with: .color(Color.textPrimary.opacity(0.5 * dim)), lineWidth: 1)235            }236        }237        for (text, at, rect) in labels {238            // a soft plate keeps a title readable where a link passes behind it239            context.fill(Path(roundedRect: rect, cornerRadius: 5), with: .color(Color.appBackground.opacity(0.78)))240            context.draw(text, at: at, anchor: .center)241        }242    }243244    /// The project's own colour when the server gives one (`#RRGGBB`); otherwise a stable muted hue per project;245    /// nil (neutral) for a conversation outside any project.246    static func projectColor(_ raw: String?, id: String?) -> Color? {247        if let raw, let c = color(hex: raw) { return c }248        guard let id else { return nil }249        let palette = ["#5FA8D3", "#6CC5A0", "#D9A05B", "#C98BB9", "#8FB96A", "#D98880"].compactMap(color(hex:))250        return palette[Int(id.utf8.reduce(UInt32(0)) { ($0 &* 31) &+ UInt32($1) } % UInt32(palette.count))]251    }252253    /// `#RGB`, `#RRGGBB` or `RRGGBB`; nil for anything else (a named token of another client is not guessed).254    static func rgb(hex: String) -> (r: Double, g: Double, b: Double)? {255        var s = hex.trimmingCharacters(in: .whitespaces)256        if s.hasPrefix("#") { s.removeFirst() }257        if s.count == 3 { s = s.map { "\($0)\($0)" }.joined() }258        guard s.count == 6, let v = UInt32(s, radix: 16) else { return nil }259        return (Double((v >> 16) & 0xFF) / 255, Double((v >> 8) & 0xFF) / 255, Double(v & 0xFF) / 255)260    }261    static func color(hex: String) -> Color? { rgb(hex: hex).map { Color(red: $0.r, green: $0.g, blue: $0.b) } }262263    // MARK: legend, hint, selection card264265    private func legend(_ model: ConstellationModel) -> some View {266        let basis = model.graph?.basis ?? [:]267        let present = Set(model.graph?.links.map(\.kind) ?? [])268        let kinds = ["branch", "project", "topic"].filter { present.contains($0) || basis[$0] != nil }269        return VStack(alignment: .leading, spacing: legendOpen ? 10 : 0) {270            Button { withAnimation(Motion.snappy(reduceMotion)) { legendOpen.toggle() } } label: {271                HStack(spacing: 12) {272                    ForEach(kinds, id: \.self) { k in273                        HStack(spacing: 5) { LinkSample(kind: k); Text(Self.kindLabel(k)).font(.spCaption).foregroundStyle(Color.textSecondary) }274                    }275                    Spacer(minLength: 4)276                    Image(systemName: "chevron.down").font(.system(size: 10, weight: .bold)).foregroundStyle(Color.muted).rotationEffect(.degrees(legendOpen ? 180 : 0))277                }278                .frame(minHeight: 44).contentShape(.rect)279            }280            .buttonStyle(.plain)281            .accessibilityLabel(String(localized: "Légende des liens"))282            .accessibilityHint(legendOpen ? String(localized: "Masque les explications") : String(localized: "Affiche ce sur quoi chaque lien est fondé"))283            .accessibilityIdentifier("constellation.legend")284            if legendOpen {285                VStack(alignment: .leading, spacing: 8) {286                    ForEach(kinds, id: \.self) { k in287                        if let text = basis[k] {288                            VStack(alignment: .leading, spacing: 2) {289                                Text(Self.kindLabel(k)).font(.spMicro).textCase(.uppercase).tracking(0.3).foregroundStyle(Color.muted)290                                Text(text).font(.caption).foregroundStyle(Color.textSecondary).fixedSize(horizontal: false, vertical: true)291                            }292                            .accessibilityElement(children: .combine)293                        }294                    }295                    Text("Taille d’un point : nombre de messages. Couleur : projet. Anneau : conversation épinglée ou favorite.").font(.caption2).foregroundStyle(Color.muted).fixedSize(horizontal: false, vertical: true)296                    SourceNote(text: String(localized: "Liens calculés par le serveur ; les explications ci-dessus sont les siennes."))297                }298                .padding(.bottom, 12)299                .transition(.opacity)300            }301        }302        .padding(.horizontal, 14)303        .floatSurface(cornerRadius: Radius.card)304        .frame(maxWidth: 520)305    }306307    static func kindLabel(_ k: String) -> String {308        switch k { case "branch": String(localized: "Branche"); case "project": String(localized: "Projet"); case "topic": String(localized: "Sujet proche"); default: k }309    }310311    private func hint(_ model: ConstellationModel) -> some View {312        HStack(spacing: 8) {313            if model.isLoading || model.isSettling { ProgressView().controlSize(.mini) }314            Text("\(model.nodes.count) conversation(s) · \(model.graph?.links.count ?? 0) lien(s)").font(.spCaption).foregroundStyle(Color.textSecondary).monospacedDigit()315            if zoom != 1 || pan != .zero {316                Button { withAnimation(Motion.smooth(reduceMotion)) { resetView() } } label: { Text("Recentrer").font(.spCaption).frame(minHeight: 44).contentShape(.rect) }317                    .accessibilityIdentifier("constellation.recenter")318            }319        }320        .padding(.horizontal, 14).frame(minHeight: 36)321        .floatSurface(cornerRadius: 18)322    }323324    private func card(_ n: Constellation.Node, _ model: ConstellationModel) -> some View {325        VStack(alignment: .leading, spacing: 10) {326            HStack(alignment: .top, spacing: 8) {327                VStack(alignment: .leading, spacing: 4) {328                    Text(n.title).font(.spHeading).foregroundStyle(Color.textPrimary).lineLimit(2)329                    HStack(spacing: 8) {330                        if let p = n.projectName {331                            HStack(spacing: 5) { Circle().fill(Self.projectColor(n.projectColor, id: n.projectId) ?? Color.muted).frame(width: 7, height: 7); Text(p).font(.caption).foregroundStyle(Color.textSecondary).lineLimit(1) }332                        }333                        if let label = n.branchLabel, !label.isEmpty { Label(label, systemImage: "arrow.triangle.branch").font(.caption).foregroundStyle(Color.muted).lineLimit(1) }334                        else if n.parentId != nil { Label("branche", systemImage: "arrow.triangle.branch").font(.caption).foregroundStyle(Color.muted) }335                    }336                }337                Spacer(minLength: 4)338                Button { withAnimation(Motion.snappy(reduceMotion)) { model.selection = nil } } label: {339                    Image(systemName: "xmark").font(.system(size: 11, weight: .bold)).foregroundStyle(Color.textSecondary).frame(width: 28, height: 28).background(Color.surface2, in: .circle).frame(width: 44, height: 44).contentShape(.rect)340                }341                .buttonStyle(PressScale()).accessibilityLabel(String(localized: "Désélectionner"))342            }343            if let id = n.modelId {344                let who = ModelIdentity(model: env.catalog.model(id), modelId: id, provider: nil)345                ModelChip(logo: who.logo, creatorName: who.creatorName, name: who.name, route: who.route, markSize: 15, font: .spCaption)346            }347            HStack(spacing: 12) {348                FactCell(title: String(localized: "Messages"), value: n.messages.formatted())349                FactCell(title: String(localized: "Coût enregistré"), value: Format.usd(n.costUsd))350                FactCell(title: String(localized: "Activité"), value: n.lastAt.map { Format.relative($0) } ?? "—")351            }352            Button { open(n) } label: {353                Label("Ouvrir", systemImage: "arrow.up.forward").font(.subheadline.weight(.semibold)).foregroundStyle(.white)354                    .frame(maxWidth: .infinity).frame(minHeight: 44).background(Color.accentColor, in: .capsule)355            }356            .buttonStyle(PressScale(scale: 0.97))357            .accessibilityIdentifier("constellation.open")358        }359        .padding(.leading, 16).padding(.trailing, 6).padding(.top, 8).padding(.bottom, 14)360        .padding(.trailing, 10)361        .floatSurface(cornerRadius: Radius.float)362        .frame(maxWidth: 520)363        .accessibilityElement(children: .contain)364    }365366    private func open(_ n: Constellation.Node) {367        env.haptics.tap()368        env.open(n.id); onOpen()369        env.router.sheet = nil370        dismiss()371    }372373    // MARK: list alternative and empty state374375    private func nodeList(_ model: ConstellationModel) -> some View {376        List {377            Section {378                ForEach(model.nodes.sorted { ($0.lastAt ?? .distantPast) > ($1.lastAt ?? .distantPast) }) { n in379                    Button { open(n) } label: {380                        HStack(spacing: 12) {381                            Circle().fill(Self.projectColor(n.projectColor, id: n.projectId) ?? Color.muted.opacity(0.6)).frame(width: 10, height: 10)382                            VStack(alignment: .leading, spacing: 2) {383                                Text(n.title).font(.body).foregroundStyle(Color.textPrimary).lineLimit(1)384                                let links = model.graph?.links.filter { $0.source == n.id || $0.target == n.id }.count ?? 0385                                Text([n.projectName, String(localized: "\(n.messages) message(s)"), links > 0 ? String(localized: "\(links) lien(s)") : nil, n.lastAt.map { Format.relative($0) }].compactMap { $0 }.joined(separator: " · "))386                                    .font(.caption).foregroundStyle(Color.muted).lineLimit(1)387                            }388                            Spacer(minLength: 0)389                            if let m = env.catalog.model(n.modelId) { ModelMark(m, size: 16) }390                        }391                        .frame(minHeight: 44).contentShape(.rect)392                    }393                    .buttonStyle(.plain)394                    .accessibilityIdentifier("constellation.row")395                }396            } footer: {397                VStack(alignment: .leading, spacing: 6) {398                    ForEach(["branch", "project", "topic"], id: \.self) { k in399                        if let text = model.graph?.basis[k] { Text("\(Self.kindLabel(k)) — \(text)").font(.caption2).foregroundStyle(Color.muted) }400                    }401                }402            }403        }404        .listStyle(.plain).scrollContentBackground(.hidden)405        .refreshable { await model.load(reduceMotion: reduceMotion) }406    }407408    @ViewBuilder private func emptyState(_ model: ConstellationModel) -> some View {409        if model.isLoading { ProgressView().controlSize(.large) }410        else if let e = model.error {411            ContentUnavailableView { Label("Constellation indisponible", systemImage: "wifi.slash") } description: { Text(e) } actions: { Button("Réessayer") { Task { await model.load(reduceMotion: reduceMotion) } } }412        } else {413            ContentUnavailableView { Label("Rien à relier pour l’instant", systemImage: "point.3.connected.trianglepath.dotted") } description: {414                Text(model.projectId == nil ? String(localized: "Les conversations du compte apparaissent ici, reliées par leurs bifurcations, leurs projets et la proximité de leurs sujets.") : String(localized: "Aucune conversation dans ce projet."))415            } actions: {416                if model.projectId != nil { Button("Tous les projets") { model.projectId = nil; Task { await model.load(reduceMotion: reduceMotion) } } }417            }418        }419    }420}421422/// The stroke of one kind of link, as drawn in the graph.423private struct LinkSample: View {424    let kind: String425    var body: some View {426        Canvas { context, size in427            var p = Path(); p.move(to: CGPoint(x: 0, y: size.height / 2)); p.addLine(to: CGPoint(x: size.width, y: size.height / 2))428            switch kind {429            case "branch": context.stroke(p, with: .color(Color.textSecondary), style: StrokeStyle(lineWidth: 1.8, lineCap: .round))430            case "project": context.stroke(p, with: .color(Color.textSecondary.opacity(0.8)), style: StrokeStyle(lineWidth: 1.3, dash: [4, 3]))431            default: context.stroke(p, with: .color(Color.textSecondary.opacity(0.55)), style: StrokeStyle(lineWidth: 0.9))432            }433        }434        .frame(width: 18, height: 10)435        .accessibilityHidden(true)436    }437}438
Files main
Menu

Theme