Branchwell

Graphley / app · graphley.ai / Sources / OwnerMetricsUI / OwnerDashboard.swift

1import Charts
2import Observation
3import OwnerMetricsKit
4import SwiftUI
5
6@MainActor @Observable
7private final class DashboardState {
8 var window: MetricWindow = .month
9 var kind: MetricKind = .website
10 var snapshot: OwnerMetricsSnapshot?
11 var passkeys: [PasskeyInfo] = []
12 var loading = false
13 var unlocked = false
14 var message: String?
15 private let client = MetricsClient()
16 private let passkeyClient = PasskeyClient()
17 private let authorizer = PasskeyAuthorizer()
18 private var nonce = UUID()
19 private var started = false
20
21 func start() async {
22 guard !started else { return }
23 started = true
24 SessionKeychain.removeLegacyViewerToken()
25 await refresh()
26 }
27
28 func refresh() async {
29 let id = UUID()
30 nonce = id
31 let selected = window
32 loading = true
33 message = nil
34 if snapshot != nil { snapshot = nil }
35 defer { if nonce == id { loading = false } }
36 do {
37 guard let session = try SessionKeychain.read() else {
38 if nonce == id { unlocked = false }
39 return
40 }
41 let next = try await client.read(session: session, window: selected)
42 guard nonce == id, selected == window else { return }
43 snapshot = next
44 unlocked = true
45 passkeys = (try? await passkeyClient.passkeys(session: session)) ?? passkeys
46 } catch {
47 guard nonce == id, !Task.isCancelled else { return }
48 if (error as? MetricsError) == .unauthorizedOrDisabled { endSession() }
49 message = error.localizedDescription
50 }
51 }
52
53 func signIn() async {
54 await passkeyStep {
55 let challenge = try await self.passkeyClient.signInChallenge()
56 let assertion = try await self.authorizer.assertion(for: challenge)
57 try SessionKeychain.save(try await self.passkeyClient.signIn(challengeID: challenge.id, assertion: assertion))
58 }
59 }
60
61 /// Adds a passkey with a one-time setup link, or a second passkey while signed in.
62 func addPasskey(setupCode: String? = nil) async {
63 await passkeyStep {
64 let session = setupCode == nil ? try SessionKeychain.read() : nil
65 let challenge = try await self.passkeyClient.registrationChallenge(setupCode: setupCode, session: session)
66 let registration = try await self.authorizer.registration(for: challenge)
67 if let started = try await self.passkeyClient.register(challengeID: challenge.id, registration: registration, session: session) {
68 try SessionKeychain.save(started)
69 }
70 }
71 }
72
73 func remove(_ passkey: PasskeyInfo) async {
74 await passkeyStep {
75 guard let session = try SessionKeychain.read() else { throw MetricsError.unauthorizedOrDisabled }
76 try await self.passkeyClient.remove(id: passkey.id, session: session)
77 }
78 }
79
80 func open(_ url: URL) async {
81 guard let code = PasskeyClient.setupCode(from: url) else { return }
82 await addPasskey(setupCode: code)
83 }
84
85 func signOut() async {
86 let session = try? SessionKeychain.read()
87 endSession()
88 if let session { await passkeyClient.signOut(session: session) }
89 }
90
91 private func passkeyStep(_ step: @escaping @MainActor () async throws -> Void) async {
92 guard !loading else { return }
93 loading = true
94 message = nil
95 do {
96 try await step()
97 loading = false
98 await refresh()
99 } catch {
100 loading = false
101 guard !(error is CancellationError) else { return }
102 message = error.localizedDescription
103 }
104 }
105
106 private func endSession() {
107 nonce = UUID()
108 snapshot = nil
109 passkeys = []
110 unlocked = false
111 loading = false
112 do { try SessionKeychain.remove() } catch { message = error.localizedDescription }
113 }
114}
115
116public struct OwnerDashboard: View {
117 @Environment(\.scenePhase) private var scenePhase
118 @State private var state = DashboardState()
119
120 public init() {}
121
122 public var body: some View {
123 let locked = !state.unlocked
124 Group {
125 #if os(iOS)
126 if scenePhase != .active {
127 Color.clear.overlay { Image(systemName: "lock.fill").font(.title).foregroundStyle(.secondary) }
128 .accessibilityLabel("Graphley privacy cover")
129 } else {
130 dashboard(locked: locked)
131 }
132 #else
133 dashboard(locked: locked)
134 #endif
135 }
136 .task { await state.start() }
137 .onOpenURL { url in Task { await state.open(url) } }
138 #if os(iOS)
139 .onChange(of: scenePhase) { _, newPhase in
140 if newPhase == .active && state.unlocked && !state.loading {
141 Task { await state.refresh() }
142 }
143 }
144 #endif
145 }
146
147 private func dashboard(locked: Bool) -> some View {
148 ScrollView {
149 VStack(alignment: .leading, spacing: 22) {
150 HStack {
151 Label("Owner dashboard", systemImage: "lock.shield")
152 .font(.caption.weight(.semibold))
153 .foregroundStyle(.secondary)
154 Spacer()
155 if !locked {
156 Menu {
157 Button("Refresh counts", systemImage: "arrow.clockwise") { Task { await state.refresh() } }
158 Button("Add a passkey", systemImage: "person.badge.key") { Task { await state.addPasskey() } }
159 Button("Sign out", systemImage: "rectangle.portrait.and.arrow.right", role: .destructive) {
160 Task { await state.signOut() }
161 }
162 } label: { Label("Dashboard actions", systemImage: "ellipsis.circle").labelStyle(.iconOnly) }
163 .accessibilityLabel("Dashboard actions")
164 }
165 }
166 VStack(alignment: .leading, spacing: 4) {
167 Text("Graphley").font(.system(size: 42, weight: .semibold, design: .rounded))
168 .accessibilityAddTraits(.isHeader)
169 Text("First-party counts from Project ATOM")
170 .foregroundStyle(.secondary)
171 }
172 if locked {
173 accessCard
174 } else {
175 counts
176 passkeyList
177 }
178 if let message = state.message {
179 Label(message, systemImage: "exclamationmark.circle")
180 .font(.callout).foregroundStyle(.secondary)
181 }
182 Text("Aggregate counts only. No visitor profiles or URL-level reports.")
183 .font(.caption).foregroundStyle(.secondary)
184 }
185 .frame(maxWidth: 900)
186 .padding(24)
187 .frame(maxWidth: .infinity)
188 }
189 .background(.background)
190 .refreshable { if state.unlocked { await state.refresh() } }
191 }
192
193 private var accessCard: some View {
194 VStack(alignment: .leading, spacing: 12) {
195 Text("Private access").font(.title2.weight(.semibold))
196 Text("Sign in with your passkey to read counts. Graphley keeps only a sign-in session in this device’s Keychain.")
197 .foregroundStyle(.secondary)
198 HStack {
199 Button("Sign in with passkey", systemImage: "person.badge.key") { Task { await state.signIn() } }
200 .buttonStyle(.borderedProminent)
201 .disabled(state.loading)
202 .accessibilityIdentifier("graphley.signInWithPasskey")
203 if state.loading { ProgressView().controlSize(.small).accessibilityLabel("Checking your passkey") }
204 }
205 Text("First time on this account? Open your one-time Graphley setup link on this device to add a passkey.")
206 .font(.caption).foregroundStyle(.secondary)
207 }
208 .frame(maxWidth: .infinity, alignment: .leading)
209 .padding(20)
210 .background(.quaternary, in: RoundedRectangle(cornerRadius: 14))
211 }
212
213 private var passkeyList: some View {
214 VStack(alignment: .leading, spacing: 10) {
215 HStack {
216 Text("Passkeys").font(.headline).accessibilityAddTraits(.isHeader)
217 Spacer()
218 Button("Add a passkey", systemImage: "plus") { Task { await state.addPasskey() } }
219 .disabled(state.loading)
220 }
221 ForEach(state.passkeys) { passkey in
222 HStack {
223 VStack(alignment: .leading, spacing: 2) {
224 Text("Added \(passkey.createdAt.prefix(10))")
225 Text(passkey.lastUsedAt.map { "Last used \($0.prefix(10))" } ?? "Not used to sign in yet")
226 .font(.caption).foregroundStyle(.secondary)
227 }
228 Spacer()
229 Button("Remove", systemImage: "trash", role: .destructive) { Task { await state.remove(passkey) } }
230 .labelStyle(.iconOnly)
231 .disabled(state.loading || state.passkeys.count < 2)
232 .accessibilityLabel("Remove passkey added \(passkey.createdAt.prefix(10))")
233 }
234 }
235 Text(state.passkeys.count < 2
236 ? "Add a second passkey as your recovery. Your last passkey can’t be removed."
237 : "Any of these passkeys can sign in to Graphley.")
238 .font(.caption).foregroundStyle(.secondary)
239 }
240 .frame(maxWidth: .infinity, alignment: .leading)
241 .padding(14)
242 .background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
243 }
244
245 private var counts: some View {
246 @Bindable var state = state
247 return VStack(alignment: .leading, spacing: 14) {
248 Picker("Date range", selection: $state.window) {
249 ForEach(MetricWindow.allCases) { Text($0.title).tag($0) }
250 }
251 .pickerStyle(.segmented)
252 .accessibilityLabel("Count date range")
253 .onChange(of: state.window) { _, _ in Task { await state.refresh() } }
254
255 if let snapshot = state.snapshot {
256 Text("\(snapshot.since) to \(snapshot.through) UTC")
257 .font(.caption).foregroundStyle(.secondary)
258 HStack(spacing: 12) {
259 ForEach(MetricKind.allCases) { kind in
260 Button {
261 state.kind = kind
262 } label: {
263 VStack(alignment: .leading, spacing: 4) {
264 Text(kind.countLabel).font(.caption).foregroundStyle(.secondary)
265 Text(snapshot.hasData(kind) ? snapshot.total(kind).formatted() : "Not reported")
266 .font(.title3.weight(.semibold)).foregroundStyle(.primary)
267 .lineLimit(1).minimumScaleFactor(0.7)
268 }
269 .frame(maxWidth: .infinity, alignment: .leading)
270 .padding(14)
271 .background(state.kind == kind ? Color.accentColor.opacity(0.14) : Color.secondary.opacity(0.08),
272 in: RoundedRectangle(cornerRadius: 12))
273 }
274 .buttonStyle(.plain)
275 .accessibilityAddTraits(state.kind == kind ? .isSelected : [])
276 }
277 }
278 if snapshot.hasData(state.kind) {
279 trend(snapshot)
280 propertyBreakdown(snapshot)
281 } else {
282 ContentUnavailableView(
283 state.kind == .website ? "No site counts yet" : "No app counts yet",
284 systemImage: "chart.bar",
285 description: Text("Only new first-party counts will appear here. Older analytics were not imported.")
286 )
287 }
288 } else if state.loading {
289 ProgressView("Loading private counts…").frame(maxWidth: .infinity)
290 } else {
291 Button("Retry", systemImage: "arrow.clockwise") { Task { await state.refresh() } }
292 .buttonStyle(.bordered)
293 }
294 }
295 }
296
297 private func trend(_ snapshot: OwnerMetricsSnapshot) -> some View {
298 VStack(alignment: .leading, spacing: 8) {
299 Text("Daily trend").font(.headline).accessibilityAddTraits(.isHeader)
300 Chart(snapshot.daily(state.kind)) { row in
301 BarMark(x: .value("Day (UTC)", row.day), y: .value(state.kind.countLabel, row.count))
302 .foregroundStyle(Color.accentColor)
303 .accessibilityLabel(row.day)
304 .accessibilityValue(row.count.formatted())
305 }
306 .chartXAxis(.hidden)
307 .frame(height: 170)
308 Text("Each bar represents one UTC day. Missing days count as zero within this range.")
309 .font(.caption).foregroundStyle(.secondary)
310 }
311 .frame(maxWidth: .infinity, alignment: .leading)
312 .padding(14)
313 .background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
314 }
315
316 private func propertyBreakdown(_ snapshot: OwnerMetricsSnapshot) -> some View {
317 VStack(alignment: .leading, spacing: 10) {
318 Text(state.kind.title).font(.headline).accessibilityAddTraits(.isHeader)
319 ForEach(snapshot.properties(state.kind)) { item in
320 HStack {
321 Text(item.title)
322 Spacer()
323 Text(item.count.formatted()).monospacedDigit()
324 }
325 .accessibilityElement(children: .combine)
326 }
327 }
328 .frame(maxWidth: .infinity, alignment: .leading)
329 .padding(14)
330 .background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
331 }
332}