Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Browser9// File : SPBrowser/Core/Aura/Constellation.swift10// Module : SPBrowser11// Repository : https://git.spboucher.ai/sp-browser12// Created : 2026-11-1913// Last Modified : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreGraphics88import Foundation8990/// One tab as the constellation sees it. The Mac and iOS apps both map their tabs to this.91struct ConstellationItem: Equatable, Identifiable, Sendable {92 var id: UUID93 var title: String94 var url: String?95 var groupID: UUID?96 var groupName: String?97 var colorIndex: Int?98 /// The tab this one was opened from, when known.99 var parentID: UUID?100 var workspaceID: UUID?101 var isPinned = false102 var isPrivate = false103 var lastActive = Date.distantPast104105 var host: String { url.flatMap { URL(string: $0)?.host } ?? "" }106 var domain: String { host.isEmpty ? "" : URLInspector.registrableDomain(of: host) }107}108109/// Tabs laid out as constellations: one cluster per tab group, per site shared by several tabs, and one for the rest.110/// The layout is deterministic (same tabs → same picture) and has no dependency on any UI framework.111struct ConstellationMap: Equatable, Sendable {112 enum ClusterKind: String, Sendable { case group, domain, loose }113 struct Cluster: Equatable, Identifiable, Sendable {114 var id: String115 var kind: ClusterKind116 var label: String117 var colorIndex: Int118 var center: CGPoint119 var radius: CGFloat120 var members: [UUID]121 var groupID: UUID?122 }123 enum LinkKind: String, Sendable { case parent, group, domain }124 struct Link: Equatable, Hashable, Sendable {125 var from: UUID126 var to: UUID127 var kind: LinkKind128 }129130 var clusters: [Cluster] = []131 var positions: [UUID: CGPoint] = [:]132 var links: [Link] = []133 var bounds: CGRect = .zero134 /// Above this many tabs the views drop thumbnails and secondary links.135 var isLightweight = false136137 static let lightweightThreshold = 60138139 /// - Parameter cardSize: size of one tab card in layout units; spacing derives from it.140 init(items: [ConstellationItem], cardSize: CGSize = CGSize(width: 168, height: 118)) {141 guard !items.isEmpty else { return }142 isLightweight = items.count > Self.lightweightThreshold143 let step = max(cardSize.width, cardSize.height) * (isLightweight ? 0.80 : 1.22)144145 // 1. Membership: explicit groups first, then sites with at least two tabs, then everything else.146 var buckets: [(id: String, kind: ClusterKind, label: String, color: Int, group: UUID?, members: [ConstellationItem])] = []147 var remaining = items148 let grouped = Dictionary(grouping: remaining.filter { $0.groupID != nil }, by: { $0.groupID! })149 for (groupID, members) in grouped.sorted(by: { $0.key.uuidString < $1.key.uuidString }) {150 buckets.append(("g:" + groupID.uuidString, .group, members.first?.groupName ?? "", members.first?.colorIndex ?? 0, groupID, members))151 }152 remaining.removeAll { $0.groupID != nil }153 let byDomain = Dictionary(grouping: remaining.filter { !$0.domain.isEmpty }, by: \.domain)154 for (domain, members) in byDomain.sorted(by: { $0.key < $1.key }) where members.count >= 2 {155 buckets.append(("d:" + domain, .domain, domain, Self.stableColor(domain), nil, members))156 remaining.removeAll { $0.domain == domain }157 }158 if !remaining.isEmpty { buckets.append(("loose", .loose, "", 0, nil, remaining)) }159160 // 2. Inside a cluster: a sunflower spiral, most recently used tab at the centre.161 var local: [String: [UUID: CGPoint]] = [:]162 var radii: [String: CGFloat] = [:]163 for bucket in buckets {164 let ordered = bucket.members.sorted { ($0.isPinned ? 1 : 0, $0.lastActive, $0.id.uuidString) > ($1.isPinned ? 1 : 0, $1.lastActive, $1.id.uuidString) }165 var points: [UUID: CGPoint] = [:]166 var reach: CGFloat = 0167 for (index, item) in ordered.enumerated() {168 let r = ordered.count == 1 ? 0 : step * 0.96 * CGFloat(Double(index).squareRoot())169 let angle = Double(index) * 2.399963229728653 + Double(Self.stableColor(bucket.id)) * 0.7170 let p = CGPoint(x: r * CGFloat(cos(angle)), y: r * CGFloat(sin(angle)) * 0.86)171 points[item.id] = p172 reach = max(reach, hypot(p.x, p.y))173 }174 local[bucket.id] = points175 radii[bucket.id] = reach + max(cardSize.width, cardSize.height) * 0.72176 }177178 // 3. Clusters are packed on an outward spiral, the biggest first, never overlapping.179 var placed: [(center: CGPoint, radius: CGFloat)] = []180 let order = buckets.sorted { ($0.members.count, $1.id) > ($1.members.count, $0.id) }181 for bucket in order {182 let radius = radii[bucket.id] ?? step183 var center = CGPoint.zero184 if !placed.isEmpty {185 var t = 0.0186 var found = false187 while !found && t < 4000 {188 let distance = CGFloat(18 * t.squareRoot() * 6)189 let angle = t * 0.55190 let candidate = CGPoint(x: distance * CGFloat(cos(angle)) * 1.25, y: distance * CGFloat(sin(angle)))191 if placed.allSatisfy({ hypot($0.center.x - candidate.x, $0.center.y - candidate.y) >= $0.radius + radius + step * 0.28 }) {192 center = candidate193 found = true194 }195 t += 1196 }197 }198 placed.append((center, radius))199 let members = local[bucket.id] ?? [:]200 for (id, p) in members { positions[id] = CGPoint(x: center.x + p.x, y: center.y + p.y) }201 let orderedIDs = bucket.members.sorted { hypot(members[$0.id]?.x ?? 0, members[$0.id]?.y ?? 0) < hypot(members[$1.id]?.x ?? 0, members[$1.id]?.y ?? 0) }.map(\.id)202 clusters.append(Cluster(id: bucket.id, kind: bucket.kind, label: bucket.label, colorIndex: bucket.color, center: center, radius: radius,203 members: orderedIDs, groupID: bucket.group))204 }205 clusters.sort { $0.id < $1.id }206207 // 4. Links. Parent → child always; inside a cluster each star joins its nearest already-placed neighbour (a spanning tree).208 var seen = Set<Link>()209 let known = Set(items.map(\.id))210 for item in items {211 if let parent = item.parentID, known.contains(parent), parent != item.id { seen.insert(Link(from: parent, to: item.id, kind: .parent)) }212 }213 if !isLightweight {214 for cluster in clusters where cluster.kind != .loose && cluster.members.count > 1 {215 for index in 1..<cluster.members.count {216 let id = cluster.members[index]217 guard let p = positions[id] else { continue }218 let nearest = cluster.members[0..<index].min { a, b in219 let pa = positions[a] ?? .zero, pb = positions[b] ?? .zero220 return hypot(pa.x - p.x, pa.y - p.y) < hypot(pb.x - p.x, pb.y - p.y)221 }222 guard let nearest, !seen.contains(Link(from: nearest, to: id, kind: .parent)), !seen.contains(Link(from: id, to: nearest, kind: .parent)) else { continue }223 seen.insert(Link(from: nearest, to: id, kind: cluster.kind == .group ? .group : .domain))224 }225 }226 }227 links = seen.sorted { ($0.from.uuidString, $0.to.uuidString) < ($1.from.uuidString, $1.to.uuidString) }228229 // 5. Bounds.230 var rect = CGRect.null231 for (center, radius) in placed { rect = rect.union(CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2)) }232 bounds = rect.isNull ? .zero : rect233 }234235 func cluster(containing id: UUID) -> Cluster? { clusters.first { $0.members.contains(id) } }236237 /// The cluster under a point, if any (used when a tab is dropped).238 func cluster(at point: CGPoint) -> Cluster? {239 clusters.filter { hypot($0.center.x - point.x, $0.center.y - point.y) <= $0.radius }.min { $0.radius < $1.radius }240 }241242 /// The neighbour of `id` in a direction (keyboard navigation). `dx`, `dy` are -1, 0 or 1.243 func neighbour(of id: UUID, dx: Int, dy: Int) -> UUID? {244 guard let origin = positions[id] else { return positions.keys.sorted { $0.uuidString < $1.uuidString }.first }245 var best: (UUID, CGFloat)?246 for (other, p) in positions where other != id {247 let vx = p.x - origin.x, vy = p.y - origin.y248 let along = vx * CGFloat(dx) + vy * CGFloat(dy)249 guard along > 1 else { continue }250 let across = abs(vx * CGFloat(dy) - vy * CGFloat(dx))251 let cost = along + across * 2.2252 if best == nil || cost < best!.1 || (cost == best!.1 && other.uuidString < best!.0.uuidString) { best = (other, cost) }253 }254 return best?.0255 }256257 /// Scale that makes the whole map fit `size`, within sensible limits.258 func fittingScale(in size: CGSize, padding: CGFloat = 60) -> CGFloat {259 guard bounds.width > 0, bounds.height > 0 else { return 1 }260 let s = min((size.width - padding * 2) / bounds.width, (size.height - padding * 2) / bounds.height)261 return min(max(s, 0.18), 1.15)262 }263264 static func stableColor(_ text: String) -> Int {265 var hash: UInt32 = 2166136261266 for byte in text.utf8 { hash = (hash ^ UInt32(byte)) &* 16777619 }267 return Int(hash % 6)268 }269270 static func filter(_ items: [ConstellationItem], query: String) -> Set<UUID> {271 let needle = query.trimmingCharacters(in: .whitespaces).lowercased()272 guard !needle.isEmpty else { return Set(items.map(\.id)) }273 return Set(items.filter { $0.title.lowercased().contains(needle) || ($0.url ?? "").lowercased().contains(needle) || ($0.groupName ?? "").lowercased().contains(needle) }.map(\.id))274 }275}276