Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Constellation/ConstellationModel.swift4// Description: State of the Conversation Constellation: loads the graph, runs the force layout off the main thread5// (positions published at most ~30 times per second while it settles, nothing while idle).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import CoreGraphics12import Foundation13import Observation1415@MainActor16@Observable17final class ConstellationModel {18 private(set) var graph: Constellation?19 /// Layout coordinates, one per node of `graph`, centred on (0, 0).20 private(set) var positions: [CGPoint] = []21 private(set) var isLoading = false22 private(set) var isSettling = false23 var error: String?24 var projectId: String?25 var selection: String?26 /// Height / width of the canvas: the layout stretches along the longer side.27 var aspect: Double = 1.62829 @ObservationIgnored private let api: ChatAPI30 @ObservationIgnored private var edges: [ForceLayout.Edge] = []31 @ObservationIgnored private var layoutTask: Task<Void, Never>?32 @ObservationIgnored private var generation = 03334 init(api: ChatAPI) { self.api = api }3536 var nodes: [Constellation.Node] { graph?.nodes ?? [] }37 var selectedNode: Constellation.Node? { selection.flatMap { id in nodes.first { $0.id == id } } }38 func index(of id: String) -> Int? { nodes.firstIndex { $0.id == id } }3940 func load(reduceMotion: Bool) async {41 isLoading = true; defer { isLoading = false }42 do {43 let g = try await api.constellation(limit: 120, project: projectId)44 error = nil45 if g == graph { return }46 graph = g47 if let s = selection, !g.nodes.contains(where: { $0.id == s }) { selection = nil }48 edges = ForceLayout.edges(for: g)49 start(ForceLayout(count: g.nodes.count, edges: edges, aspect: aspect), animated: !reduceMotion)50 } catch let e as APIError {51 if e.kind != .cancelled { error = e.message }52 } catch { self.error = String(localized: "Chargement impossible.") }53 }5455 /// Runs a layout on a detached task. Animated: positions arrive in frames while it settles. Otherwise the layout56 /// is computed completely before anything is shown (Reduce Motion).57 private func start(_ layout: ForceLayout, animated: Bool) {58 layoutTask?.cancel()59 generation += 160 let gen = generation61 guard layout.count > 0 else { positions = []; isSettling = false; return }62 isSettling = true63 if positions.count != layout.count && animated { positions = layout.positions }64 layoutTask = Task.detached(priority: .userInitiated) { [weak self] in65 var l = layout66 if !animated {67 l.settle()68 let final = l.positions69 await self?.publish(final, generation: gen, done: true)70 return71 }72 let clock = ContinuousClock()73 while !l.isSettled && !Task.isCancelled {74 let frameStart = clock.now75 for _ in 0..<4 where !l.isSettled { l.step() }76 let snapshot = l.positions, done = l.isSettled77 await self?.publish(snapshot, generation: gen, done: done)78 // ~30 frames per second while settling; the task ends with the layout, so nothing runs while idle79 let elapsed = clock.now - frameStart80 if elapsed < .milliseconds(33) { try? await Task.sleep(for: .milliseconds(33) - elapsed) }81 }82 }83 }8485 private func publish(_ p: [CGPoint], generation gen: Int, done: Bool) {86 guard gen == generation else { return }87 positions = p88 if done { isSettling = false }89 }9091 // MARK: dragging a node9293 /// The node follows the finger at once; the rest of the graph is left as it is until the drag ends.94 func drag(_ index: Int, to point: CGPoint) {95 guard positions.indices.contains(index) else { return }96 layoutTask?.cancel(); generation += 1; isSettling = false97 positions[index] = point98 }99100 /// The drag ended: the neighbours relax around the node's new place.101 func endDrag(_ index: Int, reduceMotion: Bool) {102 guard positions.indices.contains(index), positions.count > 1 else { return }103 var l = ForceLayout(positions: positions, edges: edges, alpha: 0.3, aspect: aspect)104 l.pinned = [index]105 start(l, animated: !reduceMotion)106 }107108 func stop() { layoutTask?.cancel(); layoutTask = nil; generation += 1; isSettling = false }109}110