Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ConstellationScreen.swift3// Description: Conversation Constellation: the owner's conversations as an interactive graph on a native Canvas (force layout computed off the main thread, pan / zoom, hover card, selection, keyboard), with an accessible list alternative.4import SwiftUI5import AppKit6import SPChatCore78// MARK: - Model910@Observable final class ConstellationViewModel {11 static let limits = [40, 80, 160, 300]1213 var limit = 16014 /// nil = every project.15 var projectId: String?16 var selected: String?17 private(set) var graph: Constellation?18 /// Settled position of each node in the layout space (`layoutSize`).19 private(set) var positions: [String: CGPoint] = [:]20 private(set) var layoutSize = CGSize(width: 900, height: 620)21 private(set) var loading = false22 private(set) var error: String?23 @ObservationIgnored private var generation = 024 @ObservationIgnored private(set) var neighbours: [String: Set<String>] = [:]25 @ObservationIgnored private(set) var byId: [String: Constellation.Node] = [:]2627 /// Radius of a node from its message count (area grows with the count), 5…22 pt in the layout space.28 nonisolated static func radius(messages: Int) -> Double { min(22, 5 + 2.4 * Double(max(messages, 0)).squareRoot()) }29 /// The layout space grows with the number of nodes so that density stays readable.30 nonisolated static func layoutSize(nodes: Int) -> CGSize { let k = max(1, (Double(nodes) / 36).squareRoot()); return CGSize(width: 900 * k, height: 620 * k) }31 nonisolated static func strength(_ link: Constellation.Link) -> Double {32 switch link.kind { case "branch": 1; case "project": 0.6; default: 0.25 + 0.6 * min(max(link.weight, 0), 1) }33 }3435 /// Pure and deterministic (fixed seed): the same graph always gives the same picture.36 nonisolated static func layout(_ graph: Constellation) -> (positions: [String: CGPoint], size: CGSize) {37 let size = layoutSize(nodes: graph.nodes.count)38 let index = Dictionary(graph.nodes.enumerated().map { ($1.id, $0) }, uniquingKeysWith: { a, _ in a })39 let edges = graph.links.compactMap { l -> ForceLayout.Edge? in40 guard let a = index[l.source], let b = index[l.target] else { return nil }41 return ForceLayout.Edge(a, b, strength: strength(l))42 }43 var config = ForceLayout.Configuration(); config.seed = 7; config.spread = 0.62; config.gravity = 0.1444 let result = ForceLayout.run(radii: graph.nodes.map { radius(messages: $0.messages) }, edges: edges, width: size.width, height: size.height, configuration: config)45 guard !result.positions.isEmpty else { return ([:], size) }46 // the picture is framed on what was actually laid out, with room for the labels under the nodes47 let xs = result.positions.map(\.x), ys = result.positions.map(\.y)48 let minX = (xs.min() ?? 0) - 90, minY = (ys.min() ?? 0) - 40, maxX = (xs.max() ?? size.width) + 90, maxY = (ys.max() ?? size.height) + 5649 var out: [String: CGPoint] = [:]50 for (i, n) in graph.nodes.enumerated() where i < result.positions.count { out[n.id] = CGPoint(x: result.positions[i].x - minX, y: result.positions[i].y - minY) }51 return (out, CGSize(width: max(maxX - minX, 200), height: max(maxY - minY, 200)))52 }5354 func load(_ api: APIClient) async {55 generation += 1; let mine = generation56 loading = true; error = nil57 do {58 let g = try await api.constellation(limit: limit, projectId: projectId)59 // the simulation runs off the main thread; the graph appears settled60 let l = await Task.detached(priority: .userInitiated) { Self.layout(g) }.value61 guard mine == generation else { return }62 show(g, layout: l)63 } catch {64 guard mine == generation else { return }65 if (error as? APIError)?.kind != .cancelled { self.error = (error as? LocalizedError)?.errorDescription ?? String(describing: error) }66 }67 loading = false68 }6970 func show(_ g: Constellation, layout: (positions: [String: CGPoint], size: CGSize)) {71 graph = g; positions = layout.positions; layoutSize = layout.size; error = nil72 byId = Dictionary(g.nodes.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })73 var n: [String: Set<String>] = [:]74 for l in g.links { n[l.source, default: []].insert(l.target); n[l.target, default: []].insert(l.source) }75 neighbours = n76 if let s = selected, byId[s] == nil { selected = nil }77 }7879 func node(_ id: String?) -> Constellation.Node? { id.flatMap { byId[$0] } }8081 /// Moves the selection to the nearest node in a direction (arrow keys). `dx`, `dy` ∈ {-1, 0, 1}.82 func moveSelection(dx: Double, dy: Double) {83 guard let g = graph, !g.nodes.isEmpty else { return }84 guard let current = selected, let from = positions[current] else { selected = g.nodes.first?.id; return }85 var best: (id: String, score: Double)?86 for n in g.nodes where n.id != current {87 guard let p = positions[n.id] else { continue }88 let vx = p.x - from.x, vy = p.y - from.y89 let along = vx * dx + vy * dy90 guard along > 1 else { continue }91 let across = abs(vx * dy - vy * dx)92 let score = along + across * 2.2 // prefer what lies straight ahead93 if best == nil || score < best!.score { best = (n.id, score) }94 }95 if let best { selected = best.id }96 }97}9899// MARK: - Screen100101struct ConstellationScreen: View {102 @Bindable var window: WindowModel103 @Environment(AppEnvironment.self) private var env104 @State private var model: ConstellationViewModel105106 /// `model` lets a caller (tests, previews) show a prepared state; the screen owns a fresh one otherwise.107 init(window: WindowModel, model: ConstellationViewModel = ConstellationViewModel()) { self.window = window; _model = State(initialValue: model) }108109 var body: some View {110 VStack(alignment: .leading, spacing: DS.S.l) {111 header112 if let error = model.error { Banner(kind: .error, text: "Impossible de charger la constellation : \(error)", actionTitle: "Réessayer", action: { reload() }) }113 if let graph = model.graph {114 if graph.nodes.isEmpty {115 EmptyStateView(systemImage: "point.3.filled.connected.trianglepath.dotted", title: "Aucune conversation à relier",116 message: model.projectId == nil ? "La constellation se dessine dès que des conversations contiennent des messages." : "Ce projet n'a pas encore de conversation avec des messages.")117 .frame(maxWidth: .infinity, maxHeight: .infinity)118 } else {119 HStack(alignment: .top, spacing: DS.S.l) {120 VStack(spacing: 0) {121 ConstellationCanvas(model: model, graph: graph, open: open)122 Rectangle().fill(DS.C.border).frame(height: 1)123 ConstellationLegend(graph: graph).padding(DS.S.l)124 }125 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))126 .clipShape(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))127 .overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))128 ConstellationSidebar(model: model, graph: graph, open: open).frame(width: 290)129 }130 .frame(maxHeight: .infinity)131 }132 } else if model.error == nil {133 Text("Calcul de la constellation…").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity, maxHeight: .infinity)134 } else { Spacer() }135 }136 .padding(DS.S.xxl)137 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)138 .background(DS.C.bg)139 .task {140 if env.catalog.projects.isEmpty, !env.catalog.loaded { await env.catalog.load() }141 if model.graph == nil { await model.load(env.api) }142 }143 .onChange(of: model.limit) { reload() }144 .onChange(of: model.projectId) { reload() }145 }146147 private func reload() { Task { await model.load(env.api) } }148 private func open(_ id: String) { window.open(id) }149150 private var header: some View {151 @Bindable var model = model152 return HStack(alignment: .firstTextBaseline, spacing: DS.S.l) {153 VStack(alignment: .leading, spacing: 2) {154 Text("Constellation").font(DS.F.title).foregroundStyle(DS.C.text)155 Text(summary).font(DS.F.uiRegular).foregroundStyle(DS.C.text2).lineLimit(2)156 }157 Spacer(minLength: DS.S.l)158 if model.loading { Text("Actualisation…").font(DS.F.caption).foregroundStyle(DS.C.muted) }159 Picker("Projet", selection: $model.projectId) {160 Text("Tous les projets").tag(String?.none)161 ForEach(env.catalog.projects) { Text($0.name).tag(String?.some($0.id)) }162 }163 .labelsHidden().fixedSize().accessibilityLabel("Projet").accessibilityIdentifier("constellation-project")164 Picker("Nombre de conversations", selection: $model.limit) {165 ForEach(ConstellationViewModel.limits, id: \.self) { Text("\($0) plus récentes").tag($0) }166 }167 .labelsHidden().fixedSize().accessibilityLabel("Nombre de conversations").accessibilityIdentifier("constellation-limit")168 IconButton(systemImage: "arrow.clockwise", label: "Recalculer la constellation") { reload() }.disabled(model.loading)169 }170 }171172 private var summary: String {173 guard let g = model.graph else { return "Tes conversations reliées par leurs bifurcations, leurs projets et leur proximité de sujet." }174 func count(_ n: Int, _ one: String, _ many: String) -> String { "\(n) \(n > 1 ? many : one)" }175 return "\(count(g.nodes.count, "conversation", "conversations")) · \(count(g.links.count, "lien", "liens")) — bifurcations, projets et proximité de sujet. Double-clic pour ouvrir."176 }177}178179// MARK: - Canvas180181private struct ConstellationCanvas: View {182 let model: ConstellationViewModel183 let graph: Constellation184 let open: (String) -> Void185 @Environment(\.accessibilityReduceMotion) private var reduceMotion186 @Environment(AppEnvironment.self) private var env187 @State private var zoom: CGFloat = 1188 @State private var zoomAtGestureStart: CGFloat?189 @State private var pan: CGSize = .zero190 @State private var panAtGestureStart: CGSize?191 @State private var hovered: String?192 @State private var pointer: CGPoint?193 @State private var wheel = ScrollWheelMonitor()194 @FocusState private var focused: Bool195196 /// Layout space → view space.197 private struct Projection {198 let scale: CGFloat199 let origin: CGPoint200 init(view: CGSize, layout: CGSize, zoom: CGFloat, pan: CGSize) {201 let fit = min(view.width / max(layout.width, 1), view.height / max(layout.height, 1))202 scale = max(fit, 0.01) * zoom203 origin = CGPoint(x: view.width / 2 + pan.width - layout.width * scale / 2, y: view.height / 2 + pan.height - layout.height * scale / 2)204 }205 func point(_ p: CGPoint) -> CGPoint { CGPoint(x: origin.x + p.x * scale, y: origin.y + p.y * scale) }206 /// Nodes shrink and grow less than distances, so that a zoomed-out graph stays legible.207 func radius(_ r: Double) -> CGFloat { max(3.5, CGFloat(r) * min(max(scale, 0.55), 1.8)) }208 }209210 var body: some View {211 GeometryReader { geo in212 let projection = Projection(view: geo.size, layout: model.layoutSize, zoom: zoom, pan: pan)213 let focus = hovered ?? model.selected214 ZStack(alignment: .topLeading) {215 Canvas { ctx, _ in draw(&ctx, projection, focus: focus) }216 .accessibilityLabel("Graphe de \(graph.nodes.count) conversations et \(graph.links.count) liens. La liste à droite donne les mêmes conversations.")217 if let id = hovered, let node = model.node(id), let p = model.positions[id] {218 let at = projection.point(p)219 ConstellationCard(node: node, links: model.neighbours[id]?.count ?? 0, hint: true)220 .frame(width: 250)221 .position(x: min(max(at.x, 135), max(geo.size.width - 135, 135)), y: cardY(at.y, nodeRadius: projection.radius(ConstellationViewModel.radius(messages: node.messages)), height: geo.size.height))222 .allowsHitTesting(false).transition(.opacity)223 }224 controls.padding(DS.S.m).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)225 }226 .contentShape(Rectangle())227 .onContinuousHover { phase in228 switch phase {229 case .active(let location): pointer = location; hovered = hit(location, projection)230 case .ended: pointer = nil; hovered = nil231 }232 }233 .onTapGesture(count: 2, coordinateSpace: .local) { location in if let id = hit(location, projection) { model.selected = id; open(id) } }234 .onTapGesture(count: 1, coordinateSpace: .local) { location in focused = true; model.selected = hit(location, projection) }235 .gesture(DragGesture(minimumDistance: 3).onChanged { g in236 let start = panAtGestureStart ?? pan; panAtGestureStart = start237 pan = CGSize(width: start.width + g.translation.width, height: start.height + g.translation.height)238 }.onEnded { _ in panAtGestureStart = nil })239 .gesture(MagnifyGesture().onChanged { g in240 let start = zoomAtGestureStart ?? zoom; zoomAtGestureStart = start241 setZoom(start * g.magnification, around: g.startLocation, in: geo.size)242 }.onEnded { _ in zoomAtGestureStart = nil })243 .focusable().focused($focused).focusEffectDisabled()244 .onKeyPress(keys: [.leftArrow, .rightArrow, .upArrow, .downArrow, .return, .escape]) { press in245 switch press.key {246 case .leftArrow: model.moveSelection(dx: -1, dy: 0)247 case .rightArrow: model.moveSelection(dx: 1, dy: 0)248 case .upArrow: model.moveSelection(dx: 0, dy: -1)249 case .downArrow: model.moveSelection(dx: 0, dy: 1)250 case .return: if let id = model.selected { open(id) } else { return .ignored }251 default: model.selected = nil252 }253 return .handled254 }255 .onAppear {256 wheel.start { event in257 guard let location = pointer else { return false }258 let delta = event.hasPreciseScrollingDeltas ? event.scrollingDeltaY / 240 : event.scrollingDeltaY / 12259 setZoom(zoom * (1 + delta), around: location, in: geo.size)260 return true261 }262 }263 .onDisappear { wheel.stop() }264 .onChange(of: graph) { zoom = 1; pan = .zero }265 }266 .frame(minHeight: 320)267 .clipped()268 }269270 private func cardY(_ nodeY: CGFloat, nodeRadius: CGFloat, height: CGFloat) -> CGFloat {271 let half: CGFloat = 62272 let below = nodeY + nodeRadius + 12 + half273 return below + half < height ? below : max(nodeY - nodeRadius - 12 - half, half + 4)274 }275276 private var controls: some View {277 HStack(spacing: 2) {278 IconButton(systemImage: "minus.magnifyingglass", label: "Dézoomer") { withAnimation(animation) { zoom = max(zoom / 1.3, 0.4) } }279 IconButton(systemImage: "plus.magnifyingglass", label: "Zoomer") { withAnimation(animation) { zoom = min(zoom * 1.3, 6) } }280 IconButton(systemImage: "arrow.up.left.and.arrow.down.right", label: "Ajuster à la fenêtre") { withAnimation(animation) { zoom = 1; pan = .zero } }281 }282 .padding(3).floatSurface(radius: DS.R.control, shadow: false)283 }284 private var animation: Animation { DS.Motion.resolve(DS.Motion.smooth, reduceMotion: reduceMotion) }285286 /// Zooms while keeping the point under the cursor in place.287 private func setZoom(_ value: CGFloat, around location: CGPoint, in size: CGSize) {288 let next = min(max(value, 0.4), 6)289 guard next != zoom else { return }290 let before = Projection(view: size, layout: model.layoutSize, zoom: zoom, pan: pan)291 let anchor = CGPoint(x: (location.x - before.origin.x) / before.scale, y: (location.y - before.origin.y) / before.scale)292 let after = Projection(view: size, layout: model.layoutSize, zoom: next, pan: pan)293 let moved = after.point(anchor)294 zoom = next295 pan = CGSize(width: pan.width + location.x - moved.x, height: pan.height + location.y - moved.y)296 }297298 /// The node under a point (a few points of tolerance around small nodes).299 private func hit(_ location: CGPoint, _ projection: Projection) -> String? {300 var best: (id: String, distance: CGFloat)?301 for n in graph.nodes {302 guard let p = model.positions[n.id] else { continue }303 let at = projection.point(p)304 let d = hypot(at.x - location.x, at.y - location.y)305 if d <= projection.radius(ConstellationViewModel.radius(messages: n.messages)) + 5, best == nil || d < best!.distance { best = (n.id, d) }306 }307 return best?.id308 }309310 private func draw(_ ctx: inout GraphicsContext, _ projection: Projection, focus: String?) {311 let near = focus.flatMap { model.neighbours[$0] } ?? []312 // links: branch solid, project dashed, topic thin with the similarity as opacity313 for l in graph.links {314 guard let a = model.positions[l.source], let b = model.positions[l.target] else { continue }315 var path = Path(); path.move(to: projection.point(a)); path.addLine(to: projection.point(b))316 let lit = focus != nil && (l.source == focus || l.target == focus)317 let dim: Double = hovered == nil || lit ? 1 : 0.25318 let color = lit ? DS.C.accent : DS.C.text2319 switch l.kind {320 case "branch": ctx.stroke(path, with: .color(color.opacity(0.9 * dim)), style: StrokeStyle(lineWidth: lit ? 2 : 1.6, lineCap: .round))321 case "project": ctx.stroke(path, with: .color(color.opacity(0.75 * dim)), style: StrokeStyle(lineWidth: lit ? 1.6 : 1.2, lineCap: .round, dash: [5, 4]))322 default:323 let strength = min(max((l.weight - 0.5) / 0.5, 0), 1)324 ctx.stroke(path, with: .color(color.opacity((0.16 + 0.5 * strength) * dim)), style: StrokeStyle(lineWidth: lit ? 1.2 : 0.8))325 }326 }327 // nodes: size = messages, colour = the project's own colour when it has one (neutral otherwise)328 let labelAll = graph.nodes.count <= 24 || projection.scale >= 1.5329 var labels: [(node: Constellation.Node, at: CGPoint, priority: Int, dim: Double)] = []330 for n in graph.nodes {331 guard let p = model.positions[n.id] else { continue }332 let at = projection.point(p), r = projection.radius(ConstellationViewModel.radius(messages: n.messages))333 let isFocus = n.id == focus, related = isFocus || near.contains(n.id)334 let dim: Double = hovered == nil || related ? 1 : 0.28335 let rect = CGRect(x: at.x - r, y: at.y - r, width: r * 2, height: r * 2)336 let fill = Palette.hex(n.projectColor) ?? DS.C.text2337 ctx.fill(Path(ellipseIn: rect), with: .color(DS.C.surface))338 ctx.fill(Path(ellipseIn: rect), with: .color(fill.opacity((n.projectColor == nil ? 0.62 : 0.9) * dim)))339 ctx.stroke(Path(ellipseIn: rect.insetBy(dx: 0.5, dy: 0.5)), with: .color(DS.C.surface.opacity(0.9)), lineWidth: 1)340 if n.id == model.selected { ctx.stroke(Path(ellipseIn: rect.insetBy(dx: -3.5, dy: -3.5)), with: .color(DS.C.accent), lineWidth: 2) }341 else if isFocus { ctx.stroke(Path(ellipseIn: rect.insetBy(dx: -3, dy: -3)), with: .color(DS.C.accent.opacity(0.7)), lineWidth: 1.5) }342 if n.pinned || n.favorite { ctx.fill(Path(ellipseIn: CGRect(x: at.x - 1.8, y: at.y - 1.8, width: 3.6, height: 3.6)), with: .color(DS.C.surface)) }343 if hovered == nil ? (labelAll || related && focus != nil) : (near.contains(n.id) && !isFocus) {344 labels.append((n, CGPoint(x: at.x, y: at.y + r + 4), (related && focus != nil ? 1_000_000 : 0) + n.messages, dim))345 }346 }347 // labels: the most important first; one that would cover another is left out (hover shows it)348 var placed: [CGRect] = []349 for l in labels.sorted(by: { $0.priority > $1.priority }) {350 let title = l.node.title.isEmpty ? "Sans titre" : l.node.title351 let resolved = ctx.resolve(Text(title.count > 30 ? String(title.prefix(29)) + "…" : title).font(.system(size: 10.5, weight: .medium)).foregroundStyle(DS.C.text2.opacity(l.dim)))352 let size = resolved.measure(in: CGSize(width: 400, height: 40))353 let rect = CGRect(x: l.at.x - size.width / 2, y: l.at.y, width: size.width, height: size.height).insetBy(dx: -3, dy: -1)354 if placed.contains(where: { $0.intersects(rect) }) { continue }355 placed.append(rect)356 ctx.draw(resolved, at: l.at, anchor: .top)357 }358 }359}360361/// Scroll-wheel zoom: SwiftUI has no scroll-wheel gesture on macOS, so a local event monitor is installed while the362/// canvas is on screen. The handler answers whether it consumed the event (pointer over the canvas).363@MainActor private final class ScrollWheelMonitor {364 private var monitor: Any?365 func start(_ handler: @escaping (NSEvent) -> Bool) {366 stop()367 monitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { event in handler(event) ? nil : event }368 }369 func stop() { if let monitor { NSEvent.removeMonitor(monitor) }; monitor = nil }370}371372// MARK: - Hover / selection card373374private struct ConstellationCard: View {375 let node: Constellation.Node376 let links: Int377 var hint = false378 @Environment(AppEnvironment.self) private var env379 var body: some View {380 VStack(alignment: .leading, spacing: DS.S.s) {381 Text(node.title.isEmpty ? "Sans titre" : node.title).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(2).fixedSize(horizontal: false, vertical: true)382 if let m = node.modelId { ModelChip(identity: env.catalog.identity(for: m), markSize: 14, font: DS.F.caption) }383 ConstellationFacts(node: node, links: links)384 if hint { Text("Double-clic pour ouvrir").font(.system(size: 10)).foregroundStyle(DS.C.muted) }385 }386 .padding(DS.S.l).frame(maxWidth: .infinity, alignment: .leading)387 .floatSurface(radius: DS.R.card)388 }389}390391private struct ConstellationFacts: View {392 let node: Constellation.Node393 let links: Int394 private var line: String {395 var parts = ["\(node.messages) message\(node.messages > 1 ? "s" : "")"]396 if let c = node.costUsd { parts.append(Format.usd(c)) }397 if let d = node.lastAt { parts.append(Format.relative(d)) }398 return parts.joined(separator: " · ")399 }400 var body: some View {401 VStack(alignment: .leading, spacing: 2) {402 Text(line).font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.text2).lineLimit(1)403 HStack(spacing: DS.S.s) {404 if let p = node.projectName, !p.isEmpty {405 HStack(spacing: 4) { Circle().fill(Palette.hex(node.projectColor) ?? DS.C.text2).frame(width: 7, height: 7); Text(p).lineLimit(1) }406 }407 if let b = node.branchLabel, !b.isEmpty { Label(b, systemImage: "arrow.triangle.branch").lineLimit(1) } else if node.parentId != nil { Label("bifurcation", systemImage: "arrow.triangle.branch") }408 Text("\(links) lien\(links > 1 ? "s" : "")")409 }410 .font(.system(size: 10.5)).foregroundStyle(DS.C.muted)411 }412 }413}414415// MARK: - Legend416417/// Link styles with the server's own explanation of each kind, verbatim.418private struct ConstellationLegend: View {419 let graph: Constellation420 private static let kinds: [(kind: String, name: String)] = [("branch", "Bifurcation"), ("project", "Projet"), ("topic", "Sujet")]421 var body: some View {422 HStack(alignment: .top, spacing: DS.S.xl) {423 ForEach(Self.kinds, id: \.kind) { k in424 HStack(alignment: .top, spacing: DS.S.m) {425 LinkSample(kind: k.kind).frame(width: 26, height: 14)426 VStack(alignment: .leading, spacing: 1) {427 Text("\(k.name) · \(graph.links(ofKind: k.kind).count)").font(DS.F.caption).foregroundStyle(DS.C.text)428 if let basis = graph.basis[k.kind] { Text(basis).font(.system(size: 10)).foregroundStyle(DS.C.muted).lineLimit(8) }429 }430 }431 .frame(maxWidth: .infinity, alignment: .leading)432 .accessibilityElement(children: .combine)433 }434 VStack(alignment: .leading, spacing: 1) {435 Text("Nœuds").font(DS.F.caption).foregroundStyle(DS.C.text)436 Text("Taille : nombre de messages. Couleur : celle du projet quand il en a une, neutre sinon. Point central : épinglée ou favorite.").font(.system(size: 10)).foregroundStyle(DS.C.muted).lineLimit(8)437 }438 .frame(maxWidth: .infinity, alignment: .leading)439 }440 }441}442443private struct LinkSample: View {444 let kind: String445 var body: some View {446 Canvas { ctx, size in447 var p = Path(); p.move(to: CGPoint(x: 1, y: size.height / 2)); p.addLine(to: CGPoint(x: size.width - 1, y: size.height / 2))448 switch kind {449 case "branch": ctx.stroke(p, with: .color(DS.C.text2.opacity(0.9)), style: StrokeStyle(lineWidth: 1.6, lineCap: .round))450 case "project": ctx.stroke(p, with: .color(DS.C.text2.opacity(0.75)), style: StrokeStyle(lineWidth: 1.2, lineCap: .round, dash: [5, 4]))451 default: ctx.stroke(p, with: .color(DS.C.text2.opacity(0.55)), lineWidth: 0.8)452 }453 }454 .accessibilityHidden(true)455 }456}457458// MARK: - Sidebar (accessible alternative)459460/// The same conversations as a list: selection is shared with the graph, Return or the button opens.461private struct ConstellationSidebar: View {462 @Bindable var model: ConstellationViewModel463 let graph: Constellation464 let open: (String) -> Void465 @Environment(AppEnvironment.self) private var env466 @State private var filter = ""467468 private var rows: [Constellation.Node] {469 let q = filter.trimmingCharacters(in: .whitespaces)470 return q.isEmpty ? graph.nodes : graph.nodes.filter { $0.title.localizedCaseInsensitiveContains(q) || ($0.projectName ?? "").localizedCaseInsensitiveContains(q) }471 }472473 var body: some View {474 VStack(alignment: .leading, spacing: 0) {475 if let node = model.node(model.selected) {476 VStack(alignment: .leading, spacing: DS.S.m) {477 SectionCaption(text: "Sélection")478 Text(node.title.isEmpty ? "Sans titre" : node.title).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(3).fixedSize(horizontal: false, vertical: true)479 if let m = node.modelId { ModelChip(identity: env.catalog.identity(for: m), markSize: 14, font: DS.F.caption) }480 ConstellationFacts(node: node, links: model.neighbours[node.id]?.count ?? 0)481 Button { open(node.id) } label: { Label("Ouvrir la conversation", systemImage: "arrow.up.forward.app").frame(maxWidth: .infinity) }482 .buttonStyle(.borderedProminent).tint(DS.C.accent).controlSize(.regular).accessibilityIdentifier("constellation-open")483 }484 .padding(DS.S.l)485 Rectangle().fill(DS.C.border).frame(height: 1)486 }487 HStack(spacing: DS.S.m) {488 Image(systemName: "line.3.horizontal.decrease").foregroundStyle(DS.C.muted)489 TextField("Filtrer les \(graph.nodes.count) conversations", text: $filter).textFieldStyle(.plain).font(DS.F.uiRegular)490 }491 .padding(.horizontal, DS.S.l).frame(height: 34)492 Rectangle().fill(DS.C.border).frame(height: 1)493 List(rows, selection: $model.selected) { n in494 HStack(spacing: DS.S.m) {495 Circle().fill((Palette.hex(n.projectColor) ?? DS.C.text2).opacity(n.projectColor == nil ? 0.62 : 0.9)).frame(width: 8, height: 8)496 VStack(alignment: .leading, spacing: 1) {497 Text(n.title.isEmpty ? "Sans titre" : n.title).font(DS.F.uiRegular).lineLimit(1)498 Text("\(n.messages) msg · \(model.neighbours[n.id]?.count ?? 0) lien\((model.neighbours[n.id]?.count ?? 0) > 1 ? "s" : "")" + (n.projectName.map { " · \($0)" } ?? "")).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).lineLimit(1)499 }500 }501 .tag(n.id)502 .accessibilityElement(children: .ignore)503 .accessibilityLabel("\(n.title.isEmpty ? "Sans titre" : n.title), \(n.messages) messages, \(model.neighbours[n.id]?.count ?? 0) liens\(n.projectName.map { ", projet \($0)" } ?? "")")504 .accessibilityAction(named: "Ouvrir la conversation") { open(n.id) }505 }506 .listStyle(.plain).scrollContentBackground(.hidden)507 .contextMenu(forSelectionType: String.self) { ids in508 if let id = ids.first { Button("Ouvrir la conversation") { open(id) } }509 } primaryAction: { ids in if let id = ids.first { open(id) } }510 .accessibilityLabel("Conversations de la constellation")511 }512 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))513 .clipShape(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))514 .overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))515 }516}517