Repository Public
1import Foundation2import MCCCore3import Observation4import SwiftUI56/// Every section of the product. iPhone: the first four are tabs, the rest live under "More". iPad: one sidebar.7enum AppSection: String, CaseIterable, Identifiable, Codable, Sendable {8 case overview, nodes, alerts, actions9 case services, models, jobs, maintenance, network, storage, activity, audit, settings1011 var id: String { rawValue }12 var title: String { trDynamic("section." + rawValue) }13 var symbol: String {14 switch self {15 case .overview: "gauge.with.dots.needle.50percent"16 case .nodes: "desktopcomputer"17 case .alerts: "bell.badge"18 case .actions: "bolt"19 case .services: "shippingbox"20 case .models: "cpu"21 case .jobs: "list.bullet.rectangle"22 case .maintenance: "calendar"23 case .network: "network"24 case .storage: "internaldrive"25 case .activity: "clock.arrow.circlepath"26 case .audit: "checkmark.shield"27 case .settings: "gearshape"28 }29 }30 /// Sections whose root is a list of items with a detail: two panes side by side on a wide iPad.31 var isMasterDetail: Bool {32 switch self {33 case .nodes, .alerts, .actions, .services, .models, .jobs: true34 default: false35 }36 }37 static let primary: [AppSection] = [.overview, .nodes, .alerts, .actions]38 static let secondary: [AppSection] = [.services, .models, .jobs, .maintenance, .network, .storage, .activity, .audit, .settings]39 /// ⌘1 … ⌘9 on iPad.40 var shortcutIndex: Int? { AppSection.allCases.firstIndex(of: self).flatMap { $0 < 9 ? $0 + 1 : nil } }41}4243enum PhoneTab: String, CaseIterable, Identifiable, Codable, Sendable {44 case overview, nodes, alerts, actions, more45 var id: String { rawValue }46 var section: AppSection? { AppSection(rawValue: rawValue) }47 var title: String { self == .more ? tr("tab.more") : (section?.title ?? "") }48 var symbol: String { self == .more ? "ellipsis.circle" : (section?.symbol ?? "circle") }49 static func tab(for section: AppSection) -> PhoneTab { PhoneTab(rawValue: section.rawValue) ?? .more }50}5152/// A destination that can be pushed on a navigation stack (or shown in the detail pane on iPad).53enum Route: Hashable, Codable, Sendable {54 case section(AppSection)55 case node(String)56 case compare([String])57 case alert(String)58 case incident(String)59 case silences60 case action(String)61 case actionCatalog62 case approvals63 case service(String)64 case serviceLogs(id: String, name: String)65 case model(String)66 case job(String)67 case maintenanceWindow(id: String, occurrence: Date?)68 case nodeNotes(String)69 case settings(SettingsPane)7071 /// The section a route belongs to (where a deep link lands).72 var section: AppSection {73 switch self {74 case .section(let s): s75 case .node, .compare, .nodeNotes: .nodes76 case .alert, .incident, .silences: .alerts77 case .action, .actionCatalog, .approvals: .actions78 case .service, .serviceLogs: .services79 case .model: .models80 case .job: .jobs81 case .maintenanceWindow: .maintenance82 case .settings: .settings83 }84 }85}8687enum SettingsPane: String, CaseIterable, Identifiable, Codable, Sendable {88 case profile, appearance, passkeys, sessions, devices, appLock, notifications, about89 case users, invitations, agents, system90 var id: String { rawValue }91 var title: String { trDynamic("settings.pane." + rawValue) }92 var symbol: String {93 switch self {94 case .profile: "person.crop.circle"95 case .appearance: "circle.lefthalf.filled"96 case .passkeys: "person.badge.key"97 case .sessions: "rectangle.stack.person.crop"98 case .devices: "iphone.and.arrow.forward"99 case .appLock: "faceid"100 case .notifications: "bell"101 case .about: "info.circle"102 case .users: "person.2"103 case .invitations: "envelope.badge.person.crop"104 case .agents: "antenna.radiowaves.left.and.right"105 case .system: "server.rack"106 }107 }108 /// Permission that makes an admin pane visible (the server enforces; this only hides what would be refused).109 var permission: String? {110 switch self {111 case .users: "users.manage"112 case .invitations: "invitations.manage"113 case .agents: "agents.manage"114 case .system: "settings.manage"115 default: nil116 }117 }118 static let personal: [SettingsPane] = [.profile, .appearance, .passkeys, .sessions, .devices, .appLock, .notifications, .about]119 static let admin: [SettingsPane] = [.users, .invitations, .agents, .system]120}121122/// Links understood by the app: `https://clustr.spboucher.ai/open/<section>[/<uuid>]` (universal link) and the123/// same path on the Debug-only custom scheme. The setup link is handled separately (`AppModel.handle(url:)`).124enum DeepLink {125 static func route(for url: URL) -> Route? {126 var parts = url.pathComponents.filter { $0 != "/" }127 if url.scheme == AppEnvironment.debugScheme, let host = url.host() { parts.insert(host, at: 0) }128 guard parts.first == "open", parts.count >= 2 else { return nil }129 let kind = parts[1]130 let id = parts.count >= 3 ? parts[2] : nil131 if let id {132 guard UUID(uuidString: id) != nil else { return nil }133 switch kind {134 case "nodes": return .node(id)135 case "alerts": return .alert(id)136 case "incidents": return .incident(id)137 case "actions": return .action(id)138 case "services": return .service(id)139 case "models": return .model(id)140 case "jobs": return .job(id)141 case "maintenance": return .maintenanceWindow(id: id, occurrence: nil)142 default: return nil143 }144 }145 let aliases = ["incidents": AppSection.alerts]146 if let s = AppSection(rawValue: kind) ?? aliases[kind] { return .section(s) }147 return nil148 }149}150151/// What is restored when a scene comes back (`@SceneStorage`): the selected tab / section and the open item.152struct NavigationSnapshot: Codable, Equatable, Sendable {153 var tab: PhoneTab = .overview154 var section: AppSection = .overview155 var phonePaths: [String: [Route]] = [:]156 var padSelection: [String: Route] = [:]157158 var encoded: String { (try? JSONEncoder().encode(self)).map { String(decoding: $0, as: UTF8.self) } ?? "" }159 static func decode(_ s: String) -> NavigationSnapshot? {160 guard !s.isEmpty else { return nil }161 return try? JSONDecoder().decode(NavigationSnapshot.self, from: Data(s.utf8))162 }163}164165/// Navigation state of ONE scene (an iPad can show several). The phone shell reads `tab` and `phonePaths`, the166/// iPad shell `section`, `padSelection` and `padPaths`; `open` routes a destination to the right place.167@MainActor168@Observable169final class Navigator {170 enum Layout: Sendable { case phone, pad }171172 var layout: Layout = .phone173 var tab: PhoneTab = .overview {174 didSet { if let s = tab.section { section = s } else if case .section(let s)? = phonePaths[.more]?.first { section = s } }175 }176 var phonePaths: [PhoneTab: [Route]] = [:]177 var section: AppSection = .overview178 /// iPad: the item shown in the detail pane of a master-detail section.179 var padSelection: [AppSection: Route] = [:]180 /// iPad: what is pushed on top (of the detail pane for a master-detail section, of the section otherwise).181 var padPaths: [AppSection: [Route]] = [:]182 var sheet: SheetRoute?183 /// Incremented by ⌘R: the visible screen reloads.184 var refreshToken = 0185 var searchFocusToken = 0186187 func path(for tab: PhoneTab) -> Binding<[Route]> {188 Binding(get: { self.phonePaths[tab] ?? [] }, set: { self.phonePaths[tab] = $0 })189 }190 func padPath(for section: AppSection) -> Binding<[Route]> {191 Binding(get: { self.padPaths[section] ?? [] }, set: { self.padPaths[section] = $0 })192 }193194 /// The section currently on screen.195 var currentSection: AppSection {196 switch layout {197 case .pad: return section198 case .phone:199 if let s = tab.section { return s }200 if case .section(let s)? = phonePaths[.more]?.first { return s }201 return .settings202 }203 }204205 /// Shows the root of a section.206 func show(_ target: AppSection) {207 section = target208 padPaths[target] = []209 let t = PhoneTab.tab(for: target)210 phonePaths[t] = t == .more ? [.section(target)] : []211 tab = t212 }213214 /// Opens a destination from within the current section (row tap).215 func open(_ route: Route) {216 if case .section(let s) = route, layout == .pad { show(s); return }217 switch layout {218 case .phone:219 phonePaths[tab, default: []].append(route)220 case .pad:221 if section.isMasterDetail, route.section == section, Navigator.isPrimaryItem(route, of: section) {222 padSelection[section] = route223 padPaths[section] = []224 } else {225 padPaths[section, default: []].append(route)226 }227 }228 }229230 /// Jumps to a destination from outside (deep link, notification, search, overview tile).231 func go(to route: Route) {232 if case .section(let s) = route { show(s); return }233 let target = route.section234 section = target235 let t = PhoneTab.tab(for: target)236 phonePaths[t] = (t == .more ? [.section(target)] : []) + [route]237 tab = t238 if target.isMasterDetail, Navigator.isPrimaryItem(route, of: target) {239 padSelection[target] = route240 padPaths[target] = []241 } else {242 padPaths[target] = [route]243 }244 }245246 /// Back to the initial state (a session ended: the next account must not land where the previous one was).247 func reset() {248 sheet = nil249 phonePaths = [:]; padPaths = [:]; padSelection = [:]250 tab = .overview251 section = .overview252 }253254 func isSelected(_ route: Route) -> Bool { layout == .pad && padSelection[section] == route }255256 /// Items that fill the detail pane (as opposed to being pushed on top of it).257 static func isPrimaryItem(_ route: Route, of section: AppSection) -> Bool {258 switch (section, route) {259 case (.nodes, .node), (.nodes, .compare), (.alerts, .alert), (.alerts, .incident), (.actions, .action),260 (.services, .service), (.models, .model), (.jobs, .job): true261 default: false262 }263 }264265 // MARK: State restoration266267 var snapshot: NavigationSnapshot {268 get {269 var s = NavigationSnapshot(tab: tab, section: section)270 // Only the last item of each tab is kept: enough to come back to the same node, short enough to stay valid.271 for (t, p) in phonePaths where !p.isEmpty { s.phonePaths[t.rawValue] = Array(p.prefix(2)) }272 for (k, r) in padSelection { s.padSelection[k.rawValue] = r }273 return s274 }275 set {276 phonePaths = [:]277 for (k, p) in newValue.phonePaths { if let t = PhoneTab(rawValue: k) { phonePaths[t] = p } }278 tab = newValue.tab279 section = newValue.section280 padSelection = [:]281 for (k, r) in newValue.padSelection { if let s = AppSection(rawValue: k) { padSelection[s] = r } }282 padPaths = [:]283 }284 }285}286287/// Modal flows (sheets). One at a time per scene.288enum SheetRoute: Identifiable, Hashable {289 case actionRequest(type: String, target: API.ActionTarget, targetLabel: String, preset: [String: JSONValue])290 case actionPicker(target: API.ActionTarget, targetLabel: String)291 case windowEditor(windowID: String?, day: Date?, nodeID: String?)292 case noteEditor(NoteContext)293 case search294295 var id: String {296 switch self {297 case .actionRequest(let t, let target, _, _): "action-\(t)-\(target.id)"298 case .actionPicker(let target, _): "picker-\(target.id)"299 case .windowEditor(let id, _, _): "window-\(id ?? "new")"300 case .noteEditor(let c): "note-\(c.noteID ?? "new")"301 case .search: "search"302 }303 }304}305306/// What a note is attached to (window, occurrence, node) and, when editing, which note.307struct NoteContext: Hashable, Sendable {308 var noteID: String?309 var windowID: String?310 var nodeID: String?311 var occurrence: Date?312 var body: String = ""313 var pinned = false314}315