Repository Public
1import CoreGraphics2import Foundation34/// AURA Flow: the path the user followed between pages, kept as a tree of visits (search → result → article → reference…).5/// It complements the history store, which stays the chronological record: Flow only remembers *how one page led to another*.6struct FlowNode: Codable, Equatable, Identifiable, Sendable {7 enum Kind: String, Codable, Sendable { case search, page, document }8 var id: UUID = UUID()9 var url: String10 var title: String11 var parentID: UUID?12 /// The tab that made the visit (tabs come and go; this is only used while the tab lives).13 var tabID: UUID?14 var kind: Kind = .page15 var visitedAt: Date = Date()16 var visits: Int = 11718 var host: String { URL(string: url)?.host ?? "" }19 var displayTitle: String {20 if !title.isEmpty { return title }21 if kind == .search, let q = URL(string: url).flatMap(SPSearchURL.parse)?.query { return q }22 return host.isEmpty ? url : host23 }24}2526/// How a page was reached, as far as the engine can tell.27enum FlowTransition: Equatable, Sendable {28 /// A link followed in the same tab (or a form, a redirect the user caused).29 case link30 /// An address or a query typed by the user, a bookmark, a favorite: the start of a new journey.31 case typed32 /// Back, forward or reload: the user returns to a page already on the path.33 case revisit34 /// The first page of a tab opened from another tab.35 case opened(from: UUID)36}3738struct FlowTrail: Codable, Equatable, Sendable {39 static let maxNodes = 50040 var nodes: [FlowNode] = []41 /// Where each live tab currently stands on the path.42 var cursor: [UUID: UUID] = [:]4344 // MARK: Queries4546 func node(_ id: UUID?) -> FlowNode? { id.flatMap { id in nodes.first { $0.id == id } } }47 func children(of id: UUID?) -> [FlowNode] { nodes.filter { $0.parentID == id }.sorted { $0.visitedAt < $1.visitedAt } }48 var roots: [FlowNode] { nodes.filter { n in n.parentID == nil || !nodes.contains { $0.id == n.parentID } } }4950 /// From the root of the journey down to `id`.51 func path(to id: UUID) -> [FlowNode] {52 var out: [FlowNode] = []53 var current = node(id)54 var guardCount = 055 while let n = current, guardCount < 2000 { out.insert(n, at: 0); current = node(n.parentID); guardCount += 1 }56 return out57 }5859 func root(of id: UUID) -> FlowNode? { path(to: id).first }6061 func subtree(of id: UUID) -> [FlowNode] {62 var out: [FlowNode] = []63 var stack = [id]64 while let next = stack.popLast() {65 guard let n = node(next) else { continue }66 out.append(n)67 stack.append(contentsOf: children(of: next).map(\.id))68 }69 return out70 }7172 /// Nodes where the path forks: the user went back and took another way.73 var branchPoints: [FlowNode] { nodes.filter { children(of: $0.id).count > 1 } }7475 /// Journeys (root subtrees), the most recently travelled first.76 var journeys: [FlowJourney] {77 roots.map { root in78 let all = subtree(of: root.id)79 return FlowJourney(root: root, nodeCount: all.count, lastVisit: all.map(\.visitedAt).max() ?? root.visitedAt,80 branchCount: all.filter { n in all.filter { $0.parentID == n.id }.count > 1 }.count)81 }.sorted { $0.lastVisit > $1.lastVisit }82 }8384 // MARK: Recording8586 /// Records a committed navigation and returns the node the tab now stands on.87 @discardableResult88 mutating func record(url: String, title: String, tabID: UUID, transition: FlowTransition, at date: Date = Date()) -> FlowNode {89 let kind = Self.kind(of: url)90 let here = node(cursor[tabID])9192 // Same page again (reload, fragment change, title update): no new step.93 if let here, here.url == url { return touch(here.id, title: title, date: date) }9495 switch transition {96 case .revisit:97 // Back or forward: find the page on this tab's own path (ancestors first, then descendants).98 if let here {99 if let ancestor = path(to: here.id).reversed().first(where: { $0.url == url }) { cursor[tabID] = ancestor.id; return touch(ancestor.id, title: title, date: date) }100 if let descendant = subtree(of: here.id).first(where: { $0.url == url }) { cursor[tabID] = descendant.id; return touch(descendant.id, title: title, date: date) }101 }102 // Back across a typed address lands in an earlier journey of the same tab: return to that step.103 if let earlier = nodes.last(where: { $0.url == url && $0.tabID == tabID }) { cursor[tabID] = earlier.id; return touch(earlier.id, title: title, date: date) }104 return append(url: url, title: title, parent: here?.id, tabID: tabID, kind: kind, date: date)105 case .typed:106 return append(url: url, title: title, parent: nil, tabID: tabID, kind: kind, date: date)107 case .opened(let opener):108 return append(url: url, title: title, parent: cursor[opener] ?? here?.id, tabID: tabID, kind: kind, date: date)109 case .link:110 // Following the same link twice from the same page continues the existing branch instead of duplicating it.111 if let here, let existing = children(of: here.id).first(where: { $0.url == url }) { cursor[tabID] = existing.id; return touch(existing.id, title: title, date: date) }112 return append(url: url, title: title, parent: here?.id, tabID: tabID, kind: kind, date: date)113 }114 }115116 mutating func updateTitle(_ title: String, tabID: UUID) {117 guard !title.isEmpty, let id = cursor[tabID], let index = nodes.firstIndex(where: { $0.id == id }), nodes[index].title != title else { return }118 nodes[index].title = title119 }120121 /// Puts a tab on an existing node (the user picked it on the map).122 mutating func moveCursor(tabID: UUID, to nodeID: UUID) { if node(nodeID) != nil { cursor[tabID] = nodeID } }123124 mutating func tabClosed(_ tabID: UUID) { cursor[tabID] = nil }125126 mutating func removeJourney(rootID: UUID) {127 let ids = Set(subtree(of: rootID).map(\.id))128 nodes.removeAll { ids.contains($0.id) }129 cursor = cursor.filter { !ids.contains($0.value) }130 }131132 /// Forgets every step that points at `url` (history deletion); its children are re-attached to its parent.133 mutating func forget(url: String) {134 for victim in nodes.filter({ $0.url == url }) {135 for index in nodes.indices where nodes[index].parentID == victim.id { nodes[index].parentID = victim.parentID }136 cursor = cursor.filter { $0.value != victim.id }137 }138 nodes.removeAll { $0.url == url }139 }140141 /// Forgets every step on `host` and its sub-domains (site data cleared, visits to a site deleted).142 mutating func forget(host: String) {143 let key = URLInspector.registrableDomain(of: host.lowercased())144 for url in Set(nodes.filter { n in let h = n.host.lowercased(); return h == key || h.hasSuffix("." + key) }.map(\.url)) { forget(url: url) }145 }146147 mutating func forget(since date: Date?) {148 guard let date else { nodes = []; cursor = [:]; return }149 let ids = Set(nodes.filter { $0.visitedAt >= date }.map(\.id))150 for index in nodes.indices { if let p = nodes[index].parentID, ids.contains(p) { nodes[index].parentID = nil } }151 nodes.removeAll { ids.contains($0.id) }152 cursor = cursor.filter { !ids.contains($0.value) }153 }154155 private mutating func touch(_ id: UUID, title: String, date: Date) -> FlowNode {156 guard let index = nodes.firstIndex(where: { $0.id == id }) else { return FlowNode(url: "", title: "") }157 nodes[index].visits += 1158 nodes[index].visitedAt = date159 if !title.isEmpty { nodes[index].title = title }160 return nodes[index]161 }162163 private mutating func append(url: String, title: String, parent: UUID?, tabID: UUID, kind: FlowNode.Kind, date: Date) -> FlowNode {164 let node = FlowNode(url: url, title: title, parentID: parent, tabID: tabID, kind: kind, visitedAt: date)165 nodes.append(node)166 cursor[tabID] = node.id167 prune()168 return node169 }170171 /// Keeps the trail bounded: the oldest journeys go first, whole, so a path is never cut in the middle.172 private mutating func prune() {173 guard nodes.count > Self.maxNodes else { return }174 let live = Set(cursor.values.compactMap { root(of: $0)?.id })175 for journey in journeys.reversed() where nodes.count > Self.maxNodes && !live.contains(journey.root.id) {176 removeJourney(rootID: journey.root.id)177 }178 if nodes.count > Self.maxNodes * 2 { nodes.removeFirst(nodes.count - Self.maxNodes) }179 }180181 static func kind(of url: String) -> FlowNode.Kind {182 guard let parsed = URL(string: url) else { return .page }183 if SPSearchURL.isSearch(parsed) { return .search }184 if ["pdf", "epub", "doc", "docx", "ppt", "pptx", "xls", "xlsx"].contains(parsed.pathExtension.lowercased()) { return .document }185 return .page186 }187}188189struct FlowJourney: Identifiable, Equatable, Sendable {190 var root: FlowNode191 var nodeCount: Int192 var lastVisit: Date193 var branchCount: Int194 var id: UUID { root.id }195}196197/// Positions of a journey drawn as a left-to-right tree: depth is the column, each leaf takes a row.198struct FlowMap: Equatable, Sendable {199 struct Placed: Equatable, Identifiable, Sendable {200 var node: FlowNode201 var column: Int202 var row: Double203 var id: UUID { node.id }204 }205 struct Edge: Equatable, Hashable, Sendable { var from: UUID; var to: UUID }206 var placed: [Placed] = []207 var edges: [Edge] = []208 var columns = 0209 var rows = 0210211 init(trail: FlowTrail, rootID: UUID) {212 var nextRow = 0213 var result: [UUID: Placed] = [:]214 var order: [UUID] = []215 func place(_ node: FlowNode, depth: Int, seen: inout Set<UUID>) -> Double {216 guard seen.insert(node.id).inserted, depth < 400 else { return Double(nextRow) }217 let kids = trail.children(of: node.id)218 let row: Double219 if kids.isEmpty {220 row = Double(nextRow)221 nextRow += 1222 } else {223 let rows = kids.map { place($0, depth: depth + 1, seen: &seen) }224 row = (rows.first! + rows.last!) / 2225 }226 result[node.id] = Placed(node: node, column: depth, row: row)227 order.append(node.id)228 return row229 }230 guard let root = trail.node(rootID) else { return }231 var seen = Set<UUID>()232 _ = place(root, depth: 0, seen: &seen)233 placed = order.compactMap { result[$0] }.sorted { ($0.column, $0.row) < ($1.column, $1.row) }234 edges = placed.compactMap { p in p.node.parentID.flatMap { result[$0] != nil ? Edge(from: $0, to: p.node.id) : nil } }235 columns = (placed.map(\.column).max() ?? -1) + 1236 rows = max(nextRow, 1)237 }238239 func position(of id: UUID) -> Placed? { placed.first { $0.id == id } }240}241242/// Persists the trail of a profile. A private context uses `url: nil`: its trail lives in memory and dies with the window.243final class FlowStore: @unchecked Sendable {244 private let store: JSONFileStore<FlowTrail>245 init(url: URL?) { store = JSONFileStore(url: url, defaults: FlowTrail()) }246 var trail: FlowTrail { store.value }247 func update(_ body: (inout FlowTrail) -> Void) { store.update(body) }248}249