Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/ConstellationScreen.swift3// Description: The Thought Constellation screen: cluster halos, pages as stars, links that draw themselves. The caption4// always says whether the map is the server's semantic projection or a local arrangement. Compact = the map5// on top, the clusters and their pages as a list.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesDesign10import SPNotesSync11import SwiftUI1213public struct ConstellationScreen: View {14 @State private var model: ConstellationModel1516 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil) {17 _model = State(initialValue: ConstellationModel(repositories: repositories, router: router))18 }1920 public init(model: ConstellationModel) { _model = State(initialValue: model) }2122 public var body: some View {23 FeatureScaffold(title: L("Constellation"), subtitle: subtitle, phase: model.phase, freshness: model.freshness,24 retry: { Task { await model.load() } },25 actions: { FeatureIconButton("arrow.clockwise", label: L("Recalculer la carte")) { Task { await model.load(refresh: true) } } }) { sizeClass in26 FeaturePhaseView(phase: model.phase, hasData: !model.isEmpty, retry: { Task { await model.load() } }) {27 NVEmptyState(systemImage: "sparkles", title: L("Pas encore de constellation"),28 message: L("Elle apparaîtra quand vos pages seront reliées ou indexées par le serveur."))29 } content: {30 if sizeClass.isCompact { compact } else { regular }31 }32 }33 .task { if model.phase == .idle { await model.load() } }34 }3536 private var subtitle: String? {37 guard let map = model.map else { return nil }38 return LF("%lld pages · %lld regroupements", map.stars.count, map.groups.count)39 }4041 private var regular: some View {42 HStack(alignment: .top, spacing: NVSpace.lg) {43 ConstellationSurface(model: model)44 .frame(maxWidth: .infinity, maxHeight: .infinity)45 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))46 .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.line, lineWidth: 1))47 .clipShape(NVRadius.shape(NVRadius.lg))48 ScrollView { ConstellationSidePanel(model: model) }.frame(width: 320)49 }50 .padding(.horizontal, NVSpace.xl)51 .padding(.bottom, NVSpace.xl)52 }5354 private var compact: some View {55 ScrollView {56 VStack(alignment: .leading, spacing: NVSpace.lg) {57 ConstellationSurface(model: model, showsLabels: false)58 .frame(height: 300)59 .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))60 .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.line, lineWidth: 1))61 .clipShape(NVRadius.shape(NVRadius.lg))62 ConstellationSidePanel(model: model)63 }64 .padding(.horizontal, NVSpace.lg)65 .padding(.bottom, NVSpace.xl)66 }67 }68}6970/// Caption (origin of the map), selection, clusters with their pages.71struct ConstellationSidePanel: View {72 @Bindable var model: ConstellationModel7374 var body: some View {75 VStack(alignment: .leading, spacing: NVSpace.lg) {76 if let map = model.map {77 VStack(alignment: .leading, spacing: NVSpace.sm) {78 NVChip(map.isLocal ? L("Disposition locale") : L("Projection sémantique"), systemImage: map.isLocal ? "circle.grid.2x2" : "point.3.connected.trianglepath.dotted",79 tone: map.isLocal ? .warning : .accent)80 if let reason = model.fallbackReason { Text(reason).nvFont(.ui).foregroundStyle(NVColor.fg) }81 if let caption = model.caption { Text(caption).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }82 if case .server(let name, let computedAt, _) = map.origin {83 Text([name.map { LF("Empreintes : %@", $0) }, computedAt.map { LF("calculée le %@", FeatureFormat.dayTime($0)) }].compactMap { $0 }.joined(separator: " · "))84 .nvFont(.micro).foregroundStyle(NVColor.fgMuted)85 }86 }87 .padding(NVSpace.lg)88 .frame(maxWidth: .infinity, alignment: .leading)89 .nvCard()90 if let star = model.selected {91 VStack(alignment: .leading, spacing: NVSpace.md) {92 HStack(spacing: NVSpace.sm) {93 if let icon = star.icon, !icon.isEmpty { Text(icon).font(.system(size: 20)).accessibilityHidden(true) }94 Text(star.title).nvFont(.h3).foregroundStyle(NVColor.fg)95 }96 if !star.tags.isEmpty {97 HStack(spacing: NVSpace.xs) { ForEach(star.tags.prefix(4), id: \.self) { NVChip("#" + $0) } }98 }99 Text(LF("%lld lien(s)", star.degree)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)100 FeatureButton(L("Ouvrir"), systemImage: "arrow.up.forward.square", kind: .primary) { model.open(star) }101 }102 .padding(NVSpace.lg)103 .frame(maxWidth: .infinity, alignment: .leading)104 .nvCard()105 }106 ForEach(map.groups) { group in107 KnowledgeSection(title: group.label, count: group.size) {108 ForEach(model.members(of: group).prefix(8)) { star in109 KnowledgeRow(symbol: "doc.text", icon: star.icon, tint: ConstellationPalette.color(group.id), title: star.title,110 detail: star.degree > 0 ? LF("%lld lien(s)", star.degree) : nil, action: { model.select(star.id); model.open(star) })111 }112 }113 }114 let loose = model.looseStars115 if !loose.isEmpty {116 KnowledgeSection(title: L("Hors regroupement"), count: loose.count) {117 ForEach(loose.prefix(8)) { star in118 KnowledgeRow(symbol: "doc.text", icon: star.icon, title: star.title, action: { model.select(star.id); model.open(star) })119 }120 }121 }122 }123 }124 }125}126127enum ConstellationPalette {128 static func color(_ cluster: Int) -> Color {129 guard cluster >= 0 else { return NVColor.fgFaint }130 return [NVColor.accent, NVColor.ai, NVColor.success, NVColor.warning, NVColor.danger][cluster % 5]131 }132}133134struct ConstellationSurface: View {135 @Environment(\.accessibilityReduceMotion) private var reduceMotion136 @Bindable var model: ConstellationModel137 var showsLabels = true138 @State private var progress: CGFloat = 0139 @State private var lastDrag: CGSize = .zero140 @State private var lastMagnification: CGFloat = 1141142 var body: some View {143 GeometryReader { proxy in144 if let map = model.map {145 ConstellationCanvas(map: map, viewport: model.viewport, selectedId: model.selectedId, progress: progress, showsLabels: showsLabels)146 .contentShape(Rectangle())147 .gesture(DragGesture(minimumDistance: 4)148 .onChanged { value in149 model.viewport.pan(by: CGSize(width: value.translation.width - lastDrag.width, height: value.translation.height - lastDrag.height))150 lastDrag = value.translation151 }152 .onEnded { _ in lastDrag = .zero })153 .simultaneousGesture(MagnifyGesture()154 .onChanged { value in155 model.viewport.zoom(by: value.magnification / lastMagnification, anchor: value.startLocation, in: proxy.size)156 lastMagnification = value.magnification157 }158 .onEnded { _ in lastMagnification = 1 })159 .simultaneousGesture(SpatialTapGesture().onEnded { model.tap(at: $0.location, in: proxy.size) })160 .accessibilityElement()161 .accessibilityLabel(LF("Carte de %lld pages en %lld regroupements. La liste qui suit donne les mêmes pages.", map.stars.count, map.groups.count))162 .accessibilityAddTraits(.isImage)163 }164 }165 .onAppear { draw() }166 .onChange(of: model.generation) { _, _ in draw() }167 }168169 private func draw() {170 if reduceMotion { progress = 1 } else {171 progress = 0172 withNVAnimation(.slow, reduceMotion: false) { progress = 1 }173 }174 }175}176177struct ConstellationCanvas: View, @preconcurrency Animatable {178 var map: ConstellationMap179 var viewport: GraphViewport180 var selectedId: String?181 var progress: CGFloat182 var showsLabels: Bool183184 var animatableData: CGFloat {185 get { progress }186 set { progress = newValue }187 }188189 var body: some View {190 Canvas { context, size in191 let unit = GraphViewport.baseRadius(in: size) * viewport.scale192 for group in map.groups {193 let c = viewport.toView(group.center, in: size)194 let r = max(26, group.radius * unit)195 let rect = CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2)196 let colour = ConstellationPalette.color(group.id)197 context.fill(Path(ellipseIn: rect), with: .radialGradient(Gradient(colors: [colour.opacity(0.20), colour.opacity(0.03)]), center: c, startRadius: 0, endRadius: r))198 context.stroke(Path(ellipseIn: rect), with: .color(colour.opacity(0.25)), style: StrokeStyle(lineWidth: 1, dash: [3, 4]))199 }200 let positions = map.positions201 for link in map.links {202 guard let a = positions[link.source], let b = positions[link.target] else { continue }203 var path = Path()204 path.move(to: viewport.toView(a, in: size))205 path.addLine(to: viewport.toView(b, in: size))206 context.stroke(path.trimmedPath(from: 0, to: max(0, min(1, progress))), with: .color((link.isAI ? NVColor.ai : NVColor.accent).opacity(0.45)),207 style: StrokeStyle(lineWidth: 1.1, lineCap: .round, dash: link.isAI ? [4, 4] : []))208 }209 // With many pages only the best-connected ones are named (the list beside the map names them all).210 let named = map.stars.count <= 10 ? Set(map.stars.map(\.id)) : Set(map.stars.sorted { ($0.degree, $1.id) > ($1.degree, $0.id) }.prefix(6).map(\.id))211 for star in map.stars {212 let p = viewport.toView(star.position, in: size)213 let r = 4.5 + min(6, CGFloat(star.degree))214 let rect = CGRect(x: p.x - r, y: p.y - r, width: r * 2, height: r * 2)215 if star.id == selectedId {216 context.fill(Path(ellipseIn: rect.insetBy(dx: -5, dy: -5)), with: .color(NVColor.accentSoft))217 context.stroke(Path(ellipseIn: rect.insetBy(dx: -5, dy: -5)), with: .color(NVColor.accent), lineWidth: 1.5)218 }219 context.fill(Path(ellipseIn: rect), with: .color(ConstellationPalette.color(star.cluster)))220 context.stroke(Path(ellipseIn: rect), with: .color(NVColor.bgElevated), lineWidth: 1.5)221 if (showsLabels && named.contains(star.id)) || star.id == selectedId {222 let resolved = context.resolve(Text(star.title).font(NVFont.fixed(.micro)).foregroundStyle(NVColor.fgMuted))223 let measured = resolved.measure(in: CGSize(width: 150, height: 30))224 context.draw(resolved, in: CGRect(x: p.x - measured.width / 2, y: p.y + r + 3, width: measured.width, height: measured.height))225 }226 }227 if showsLabels {228 for group in map.groups {229 let c = viewport.toView(group.center, in: size)230 let r = max(26, group.radius * unit)231 let resolved = context.resolve(Text(group.label).font(NVFont.fixed(.uiStrong)).foregroundStyle(NVColor.fg))232 let measured = resolved.measure(in: CGSize(width: 200, height: 30))233 let origin = CGPoint(x: c.x - measured.width / 2, y: c.y - r - measured.height - 2)234 context.fill(Path(roundedRect: CGRect(origin: origin, size: measured).insetBy(dx: -4, dy: -1), cornerRadius: 4), with: .color(NVColor.bgElevated.opacity(0.85)))235 context.draw(resolved, in: CGRect(origin: origin, size: measured))236 }237 }238 }239 }240}241