Branchwell

Graphley / app · graphley.ai / Apps / iPhone / PhoneApp.swift

Raw 30.8 KB on d69ca9c4c8ff088be085e80dbb7478e9463bddf8
1import SwiftUI
2import AnalyticsKit
3import AnalyticsUI
4
5/// iPhone and iPad app: a viewer for the snapshot the Mac writes to the user's private iCloud database.
6/// No keys and no Google sign-in here. iPhone (and iPad in a narrow window) gets tabs; a full-size
7/// iPad window gets the Mac's sidebar layout (PadApp.swift).
8@main
9struct AnalyticsPhoneApp: App {
10 @UIApplicationDelegateAdaptor private var delegate: PhoneDelegate
11 @State private var model = PhoneModel()
12 @Environment(\.scenePhase) private var scenePhase
13 init() { Tide.registerFonts() }
14 var body: some Scene {
15 WindowGroup {
16 RootView()
17 .environment(model)
18 .tint(Tide.accent)
19 .task { delegate.onSnapshotChanged = { await model.load() } }
20 }
21 // Load every time the app comes to the front, not only on a cold launch: a phone opened
22 // before the Mac's first sync otherwise keeps showing "Waiting for your Mac".
23 .onChange(of: scenePhase, initial: true) { _, phase in
24 if phase == .active { Task { await model.load() } }
25 }
26 }
27}
28
29/// Chooses the layout from the window's width, so an iPad in Slide Over or a narrow split gets
30/// the iPhone tabs and a full-size iPad window gets the sidebar.
31struct RootView: View {
32 @Environment(PhoneModel.self) private var model
33 @Environment(\.horizontalSizeClass) private var sizeClass
34 var body: some View {
35 Group {
36 if sizeClass == .regular { PadRootView() } else { PhoneTabs() }
37 }
38 .preferredColorScheme(model.forcedScheme)
39 #if DEBUG
40 .task { await model.runTourIfAsked(pad: sizeClass == .regular) }
41 #endif
42 }
43}
44
45enum PhoneTab: Hashable { case today, dashboards, sites, apps, settings }
46
47struct PhoneTabs: View {
48 @Environment(PhoneModel.self) private var model
49 var body: some View {
50 @Bindable var model = model
51 TabView(selection: $model.tab) {
52 TodayView().tabItem { Label("Today", systemImage: "chart.xyaxis.line") }.tag(PhoneTab.today)
53 PhoneDashboardsView().tabItem { Label("Dashboards", systemImage: "rectangle.3.group") }.tag(PhoneTab.dashboards)
54 SitesView().tabItem { Label("Sites", systemImage: "list.bullet") }.tag(PhoneTab.sites)
55 PhoneAppStoreView().tabItem { Label("Apps", systemImage: "arrow.down.app") }.tag(PhoneTab.apps)
56 PhoneSettingsView().tabItem { Label("Settings", systemImage: "gearshape") }.tag(PhoneTab.settings)
57 }
58 }
59}
60
61/// Receives the silent push CloudKit sends when the Mac writes a new snapshot.
62final class PhoneDelegate: NSObject, UIApplicationDelegate {
63 var onSnapshotChanged: (@MainActor () async -> Void)?
64
65 func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
66 application.registerForRemoteNotifications()
67 return true
68 }
69
70 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult {
71 await onSnapshotChanged?()
72 return .newData
73 }
74}
75
76@MainActor @Observable
77final class PhoneModel {
78 let sync = SnapshotSync()
79 var snapshot: Snapshot?
80 var error: String?
81 var loading = false
82 /// The house iCloud Sync and Diagnostics status (Settings), same fields as Inkspring's.
83 var cloud = CloudSyncStatus()
84 /// Days shown on iPad screens (the iPhone always shows 30).
85 var range = 30
86 var tab: PhoneTab = .today
87 var todayPath: [Site] = []
88 var dashboardsPath: [String] = []
89 var sitesPath: [Site] = []
90 var padSelection: PadItem = .overview
91 /// Set by the debug tour to scroll the screen on show; nil the rest of the time.
92 var tourScroll: TourScroll?
93 var forcedScheme: ColorScheme?
94 /// Debug builds can read a copy of the Mac's store instead of iCloud (simulator demos).
95 private var demo = false
96 private let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("snapshot.json")
97
98 init() {
99 #if DEBUG
100 // `GRAPHLEY_OPEN=settings` opens Settings on launch, for screenshots of the iCloud Sync screen.
101 if ProcessInfo.processInfo.environment["GRAPHLEY_OPEN"] == "settings" { tab = .settings; padSelection = .settings }
102 // `GRAPHLEY_DEMO_WORKSPACE=/path` points at a copy of the Mac's Graphley folder
103 // (workspace.json and data.json), for simulator screenshots and videos with real numbers.
104 if let dir = ProcessInfo.processInfo.environment["GRAPHLEY_DEMO_WORKSPACE"],
105 let store = try? WorkspaceStore(folder: URL(fileURLWithPath: dir, isDirectory: true)),
106 let ws = try? store.load(), let s = try? store.snapshot(refreshedAt: ws.settings.lastRefreshAt) {
107 snapshot = s
108 demo = true
109 return
110 }
111 // `GRAPHLEY_DEMO_CONNECT=1` shows the connect-to-your-Mac screen with iCloud signed in and nothing
112 // shared yet, for the App Store screenshot of it.
113 if ProcessInfo.processInfo.environment["GRAPHLEY_DEMO_CONNECT"] != nil {
114 cloud.accountStatus = "Connected"; cloud.snapshotFound = false; cloud.lastCheck = .now
115 demo = true
116 return
117 }
118 #endif
119 snapshot = cachedSnapshot()
120 }
121
122 private func cachedSnapshot() -> Snapshot? { try? JSONDecoder.analytics.decode(Snapshot.self, from: Data(contentsOf: cacheURL)) }
123
124 func load() async {
125 guard !loading, !demo else { return }
126 loading = true; defer { loading = false }
127 cloud.lastCheck = .now
128 cloud.clearError()
129 var checkedAccount = false
130 do {
131 cloud.accountStatus = try await sync.accountStatusText()
132 checkedAccount = true
133 guard cloud.accountStatus == "Connected" else {
134 cloud.error = "This iPhone isn't signed in to iCloud. Sign in with the same Apple Account as your Mac."
135 error = snapshot == nil ? nil : "Couldn't reach iCloud. Showing the last copy."
136 return
137 }
138 let pulled = try await sync.pull()
139 cloud.lastCloudContact = .now
140 cloud.snapshotFound = pulled != nil
141 if let s = pulled {
142 snapshot = s
143 cloud.snapshotDate = s.refreshedAt
144 try? JSONEncoder.analytics.encode(s).write(to: cacheURL)
145 }
146 try? await sync.subscribe()
147 error = nil
148 } catch {
149 if !checkedAccount { cloud.accountStatus = "Unavailable" }
150 cloud.record(error)
151 self.error = snapshot == nil ? nil : "Couldn't reach iCloud. Showing the last copy."
152 }
153 }
154
155 var sites: [Site] { snapshot?.sites ?? [] }
156 var apps: [StoreApp] { snapshot?.apps ?? [] }
157 /// Apps with an App Store listing (the others are Mac downloads from their website).
158 var storeApps: [StoreApp] { apps.filter(\.hasAppStoreListing) }
159 @ObservationIgnored private var portfolioCache: (key: String, data: PortfolioData)?
160 /// The snapshot indexed for dashboards, rebuilt only when a new snapshot arrives.
161 var portfolio: PortfolioData {
162 let key = "\(snapshot?.refreshedAt.timeIntervalSince1970 ?? 0)|\(snapshot?.points.count ?? 0)"
163 if let c = portfolioCache, c.key == key { return c.data }
164 let data = snapshot.map(PortfolioData.init(snapshot:)) ?? PortfolioData(sites: [], apps: [], socials: [], points: [])
165 portfolioCache = (key, data)
166 return data
167 }
168 var dashboards: [Dashboard] { snapshot?.dashboards ?? [] }
169 var points: [DataPoint] { snapshot?.points ?? [] }
170 var days: [String] { DayKey.lastDays(range) }
171 func series(_ m: Metric, _ ids: Set<String> = [], days n: Int = 30) -> [Double] { (snapshot?.points ?? []).daily(m, subjects: ids, days: DayKey.lastDays(n)) }
172 func total(_ m: Metric, _ ids: Set<String> = [], days n: Int = 30, offset: Int = 0) -> Double {
173 (snapshot?.points ?? []).daily(m, subjects: ids, days: Array(DayKey.lastDays(n + offset).prefix(n))).reduce(0, +)
174 }
175
176 /// Daily downloads for one app: App Store first-time downloads plus Mac installers from its website,
177 /// so apps without an App Store listing (Textley, Voxley…) count too.
178 func appSeries(_ app: StoreApp, days n: Int = 30, offset: Int = 0) -> [Double] {
179 points.appDownloads(app, days: Array(DayKey.lastDays(n + offset).prefix(n)))
180 }
181 func appTotal(_ app: StoreApp, days n: Int = 30, offset: Int = 0) -> Double { appSeries(app, days: n, offset: offset).reduce(0, +) }
182 /// Every app's downloads added up per day.
183 func allAppsSeries(days n: Int = 30, offset: Int = 0) -> [Double] {
184 apps.reduce(into: Array(repeating: 0.0, count: n)) { sum, app in
185 for (i, v) in appSeries(app, days: n, offset: offset).enumerated() { sum[i] += v }
186 }
187 }
188}
189
190struct TodayView: View {
191 @Environment(PhoneModel.self) private var model
192 var body: some View {
193 @Bindable var model = model
194 NavigationStack(path: $model.todayPath) {
195 TourScrollView("today") {
196 VStack(alignment: .leading, spacing: 12) {
197 UpdatedLine()
198 if let e = model.error { Banner(text: e, kind: .error) }
199 if let s = model.snapshot {
200 if Date.now.timeIntervalSince(s.refreshedAt) > 36 * 3600 {
201 Banner(text: "These numbers are from \(s.refreshedAt.formatted(.relative(presentation: .named))). Open Graphley on your Mac to refresh.", kind: .attention)
202 }
203 VStack(alignment: .leading, spacing: 4) {
204 Text("Visitors, all sites · 30 days").font(Tide.caption).foregroundStyle(Tide.muted)
205 Text(Tide.number(model.total(.users))).font(Tide.hero).foregroundStyle(Tide.ink)
206 HStack(spacing: 5) {
207 DeltaLabel(current: model.total(.users), previous: model.total(.users, offset: 30))
208 Text("vs previous 30 days").font(Tide.caption).foregroundStyle(Tide.muted)
209 }
210 .padding(.bottom, 10)
211 TrendChart(days: DayKey.lastDays(30), values: model.series(.users), label: "Visitors").frame(height: 130)
212 }
213 .padding(16).background(Tide.surface, in: RoundedRectangle(cornerRadius: 20))
214 .overlay(RoundedRectangle(cornerRadius: 20).strokeBorder(Tide.line))
215 SectionHeader("Sites", count: model.sites.count)
216 SiteList()
217 if !model.apps.isEmpty {
218 SectionHeader("Apps", count: model.apps.count).padding(.top, 8)
219 AppList()
220 }
221 } else {
222 ConnectMacGuide { model.tab = .settings }
223 }
224 }.padding(16)
225 }
226 .refreshable { await model.load() }
227 .background(Tide.ground)
228 .navigationTitle("Today")
229 }
230 }
231}
232
233/// "SITES · 15" above a list on Today and the Apps tab.
234struct SectionHeader: View {
235 let title: String, count: Int
236 init(_ title: String, count: Int) { self.title = title; self.count = count }
237 var body: some View {
238 HStack {
239 Text(title.uppercased()).font(Tide.sectionLabel).tracking(0.8).foregroundStyle(Tide.muted)
240 Spacer()
241 Text("\(count)").font(Tide.figure(12)).foregroundStyle(Tide.muted)
242 }
243 .padding(.horizontal, 4).padding(.top, 6)
244 .accessibilityAddTraits(.isHeader)
245 .id(TourAnchor.section(title))
246 }
247}
248
249struct SiteList: View {
250 @Environment(PhoneModel.self) private var model
251 var body: some View {
252 VStack(spacing: 8) {
253 // Every site, in the same order as the Mac's sidebar, which the user sets by dragging.
254 ForEach(model.sites) { site in
255 NavigationLink(value: site) {
256 HStack {
257 Circle().fill(Tide.color(for: site)).frame(width: 8, height: 8)
258 Text(site.name).font(Tide.rowTitle).foregroundStyle(Tide.ink).lineLimit(1)
259 Spacer()
260 Sparkline(model.series(.users, [site.id]), color: Tide.color(for: site))
261 Text(Tide.number(model.total(.users, [site.id]))).font(Tide.figure(14)).foregroundStyle(Tide.ink)
262 Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Tide.muted)
263 }
264 .padding(14).background(Tide.surface, in: RoundedRectangle(cornerRadius: 14))
265 .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tide.line))
266 }
267 }
268 }
269 .navigationDestination(for: Site.self) { PhoneSiteView(site: $0) }
270 }
271}
272
273struct SitesView: View {
274 @Environment(PhoneModel.self) private var model
275 var body: some View {
276 @Bindable var model = model
277 NavigationStack(path: $model.sitesPath) {
278 TourScrollView("sites") { VStack(alignment: .leading, spacing: 12) { UpdatedLine(); SiteList() }.padding(16) }
279 .refreshable { await model.load() }
280 .background(Tide.ground).navigationTitle("Sites")
281 }
282 }
283}
284
285struct PhoneSiteView: View {
286 @Environment(PhoneModel.self) private var model
287 let site: Site
288 var body: some View {
289 let pages = (model.snapshot?.points ?? []).filter { $0.subject == site.id && ($0.breakdown?.hasPrefix("page:") ?? false) }
290 .sorted { $0.value > $1.value }.prefix(5).map { (String($0.breakdown!.dropFirst(5)), $0.value) }
291 TourScrollView("site") {
292 VStack(alignment: .leading, spacing: 12) {
293 Text("Visitors · 30 days").font(Tide.caption).foregroundStyle(Tide.muted)
294 Text(Tide.number(model.total(.users, [site.id]))).font(Tide.hero).foregroundStyle(Tide.ink)
295 DeltaLabel(current: model.total(.users, [site.id]), previous: model.total(.users, [site.id], offset: 30)).padding(.bottom, 10)
296 TrendChart(days: DayKey.lastDays(30), values: model.series(.users, [site.id]), color: Tide.color(for: site), label: "Visitors").frame(height: 160)
297 TideCard("Top pages", subtitle: "Page views, last 30 days") {
298 if pages.isEmpty { Text("No page views recorded yet.").font(Tide.secondary).foregroundStyle(Tide.muted) }
299 else { BarList(Array(pages)) }
300 }
301 }.padding(16)
302 }
303 .background(Tide.ground)
304 .navigationTitle(site.name)
305 }
306}
307
308/// Every app, App Store or Mac download from its website, with downloads over 30 days.
309struct AppList: View {
310 @Environment(PhoneModel.self) private var model
311 var body: some View {
312 VStack(spacing: 8) {
313 ForEach(model.apps) { app in
314 NavigationLink { PhoneAppView(app: app) } label: {
315 HStack {
316 Circle().fill(color(app)).frame(width: 8, height: 8)
317 VStack(alignment: .leading, spacing: 2) {
318 Text(app.shortName).font(Tide.rowTitle).foregroundStyle(Tide.ink).lineLimit(1)
319 Text((app.platforms ?? []).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1)
320 }
321 Spacer()
322 Sparkline(model.appSeries(app), color: color(app))
323 Text(Tide.number(model.appTotal(app))).font(Tide.figure(14)).foregroundStyle(Tide.ink)
324 Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Tide.muted)
325 }
326 .padding(14).background(Tide.surface, in: RoundedRectangle(cornerRadius: 14))
327 .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tide.line))
328 }
329 .buttonStyle(.plain)
330 }
331 }
332 }
333 func color(_ app: StoreApp) -> Color { app.siteID.flatMap { id in model.sites.first { $0.id == id } }.map(Tide.color(for:)) ?? Tide.accent }
334}
335
336struct PhoneAppStoreView: View {
337 @Environment(PhoneModel.self) private var model
338 var body: some View {
339 NavigationStack {
340 TourScrollView("apps") {
341 VStack(alignment: .leading, spacing: 12) {
342 UpdatedLine()
343 if model.apps.isEmpty {
344 TideCard {
345 EmptyState("No apps yet", message: "Add your apps in Graphley on your Mac. Downloads appear here after the next refresh.")
346 }
347 } else {
348 Text("Downloads, every app · 30 days").font(Tide.caption).foregroundStyle(Tide.muted)
349 Text(Tide.number(model.allAppsSeries().reduce(0, +))).font(Tide.hero).foregroundStyle(Tide.ink)
350 HStack(spacing: 5) {
351 DeltaLabel(current: model.allAppsSeries().reduce(0, +), previous: model.allAppsSeries(offset: 30).reduce(0, +))
352 Text("App Store and Mac website downloads").font(Tide.caption).foregroundStyle(Tide.muted)
353 }
354 .padding(.bottom, 10)
355 TrendChart(days: DayKey.lastDays(30), values: model.allAppsSeries(), label: "Downloads").frame(height: 160)
356 SectionHeader("Apps", count: model.apps.count)
357 AppList()
358 }
359 }.padding(16)
360 }
361 .refreshable { await model.load() }
362 .background(Tide.ground)
363 .navigationTitle("Apps")
364 }
365 }
366}
367
368/// One app on iPhone: downloads per day, where they came from, and its rating.
369struct PhoneAppView: View {
370 @Environment(PhoneModel.self) private var model
371 let app: StoreApp
372 var body: some View {
373 let platforms = sources
374 TourScrollView("app") {
375 VStack(alignment: .leading, spacing: 12) {
376 Text("Downloads · 30 days").font(Tide.caption).foregroundStyle(Tide.muted)
377 Text(Tide.number(model.appTotal(app))).font(Tide.hero).foregroundStyle(Tide.ink)
378 DeltaLabel(current: model.appTotal(app), previous: model.appTotal(app, offset: 30)).padding(.bottom, 10)
379 TrendChart(days: DayKey.lastDays(30), values: model.appSeries(app), label: "Downloads").frame(height: 160)
380 TideCard("Where downloads came from", subtitle: "Last 30 days") {
381 if platforms.isEmpty { Text("No downloads in the last 30 days.").font(Tide.secondary).foregroundStyle(Tide.muted) }
382 else { BarList(platforms) }
383 }
384 if let rating {
385 TideCard("Rating", subtitle: "App Store, all storefronts") {
386 Text(rating).font(Tide.figure(20, medium: true)).foregroundStyle(Tide.ink)
387 }
388 }
389 if let note = app.note { Text(note).font(Tide.caption).foregroundStyle(Tide.muted) }
390 }.padding(16)
391 }
392 .background(Tide.ground)
393 .navigationTitle(app.shortName)
394 }
395
396 var sources: [(String, Double)] {
397 let days = Set(DayKey.lastDays(30))
398 var totals: [String: Double] = [:]
399 if app.hasAppStoreListing {
400 for p in model.points where p.subject == app.id && p.metric == .appDownloads && days.contains(p.day) {
401 guard let b = p.breakdown, b.hasPrefix("platform:") else { continue }
402 totals[PadAppStore.platformName(b), default: 0] += p.value
403 }
404 }
405 if let web = model.points.websiteDownloads(app, days: DayKey.lastDays(30)) { totals["Mac (website)"] = web.reduce(0, +) }
406 return totals.filter { $0.value > 0 }.sorted { $0.value > $1.value }.map { ($0.key, $0.value) }
407 }
408
409 var rating: String? {
410 guard app.hasAppStoreListing,
411 let r = model.points.filter({ $0.subject == app.id && $0.metric == .rating && $0.breakdown == nil }).max(by: { $0.day < $1.day }), r.value > 0 else { return nil }
412 let count = model.points.filter { $0.subject == app.id && $0.metric == .ratingCount && $0.breakdown == nil }.max { $0.day < $1.day }?.value ?? 0
413 return r.value.formatted(.number.precision(.fractionLength(1))) + " ★ · " + Tide.number(count) + " ratings"
414 }
415}
416
417/// "Updated on your Mac 2 hours ago", under the large title on every tab.
418struct UpdatedLine: View {
419 @Environment(PhoneModel.self) private var model
420 var body: some View {
421 if let s = model.snapshot {
422 Text("Updated on your Mac \(s.refreshedAt.formatted(.relative(presentation: .named)))").font(Tide.caption).foregroundStyle(Tide.muted)
423 }
424 }
425}
426
427/// Rounded notice at the top of a tab, in the attention or error pill colors.
428struct Banner: View {
429 enum Kind { case attention, error }
430 let text: String, kind: Kind
431 var body: some View {
432 Label(text, systemImage: kind == .error ? "exclamationmark.icloud" : "clock.arrow.circlepath")
433 .font(Tide.secondary)
434 .foregroundStyle(kind == .error ? Color(light: 0x984A38, dark: 0xE58A72) : Color(light: 0x755B36, dark: 0xE3A45A))
435 .frame(maxWidth: .infinity, alignment: .leading)
436 .padding(12)
437 .background(kind == .error ? Color(light: 0xEDE2DE, dark: 0x373739) : Color(light: 0xF1EADE, dark: 0x373C34), in: RoundedRectangle(cornerRadius: 12))
438 }
439}
440
441// MARK: Tour (debug builds)
442
443enum TourAnchor: Hashable { case top, bottom, section(String) }
444struct TourScroll: Equatable { let screen: String; let anchor: TourAnchor }
445
446/// A ScrollView the debug tour can scroll, so screen recordings show the whole screen.
447/// In normal use it is a plain ScrollView.
448struct TourScrollView<Content: View>: View {
449 @Environment(PhoneModel.self) private var model
450 let screen: String
451 let content: Content
452 init(_ screen: String, @ViewBuilder content: () -> Content) { self.screen = screen; self.content = content() }
453 var body: some View {
454 ScrollViewReader { proxy in
455 ScrollView {
456 VStack(spacing: 0) {
457 Color.clear.frame(height: 0).id(TourAnchor.top)
458 content
459 Color.clear.frame(height: 0).id(TourAnchor.bottom)
460 }
461 }
462 .onChange(of: model.tourScroll) { _, target in
463 guard let target, target.screen == screen else { return }
464 withAnimation(.easeInOut(duration: 2.4)) { proxy.scrollTo(target.anchor, anchor: target.anchor == .bottom ? .bottom : .top) }
465 }
466 }
467 }
468}
469
470#if DEBUG
471extension PhoneModel {
472 /// `GRAPHLEY_TOUR=1` walks through every screen on its own, for screen recordings.
473 func runTourIfAsked(pad: Bool) async {
474 if let dir = ProcessInfo.processInfo.environment["GRAPHLEY_SHOT_DIR"] {
475 if snapshot == nil { await shot(dir, pad ? "pad-connect" : "connect"); FileManager.default.createFile(atPath: dir + "/finished.ready", contents: nil) }
476 else { await (pad ? padShots(dir) : phoneShots(dir)) }
477 return
478 }
479 guard ProcessInfo.processInfo.environment["GRAPHLEY_TOUR"] != nil, snapshot != nil else { return }
480 await pause(2.5)
481 if pad { await padTour() } else { await phoneTour() }
482 }
483
484 private func pause(_ s: Double) async { try? await Task.sleep(for: .seconds(s)) }
485 private func scroll(_ screen: String, hold: Double = 2.8) async {
486 tourScroll = TourScroll(screen: screen, anchor: .bottom); await pause(hold)
487 tourScroll = nil
488 }
489 private func top(_ screen: String) async {
490 tourScroll = TourScroll(screen: screen, anchor: .top); await pause(1.6)
491 tourScroll = nil
492 }
493
494 private func padTour() async {
495 await pause(1)
496 await scroll("pad"); await top("pad")
497 range = 90; await pause(2.2)
498 range = 7; await pause(2.2)
499 range = 30; await pause(1.2)
500 padSelection = .apps; await pause(3); await scroll("pad")
501 for d in dashboards { padSelection = .dashboard(d.id); await pause(3); await scroll("pad") }
502 for s in sites.prefix(3) { padSelection = .site(s.id); await pause(3); await scroll("pad") }
503 forcedScheme = .dark
504 padSelection = .overview; await pause(3); await scroll("pad")
505 if let s = sites.first { padSelection = .site(s.id); await pause(3) }
506 padSelection = .apps; await pause(3)
507 forcedScheme = nil
508 padSelection = .overview
509 }
510
511 /// `GRAPHLEY_SHOT_DIR=/host/path` shows each screen and writes `<name>.ready` there, so a script on the
512 /// Mac can take a `simctl io screenshot` of it (the simulator shares the Mac's file system).
513 private func shot(_ dir: String, _ name: String) async {
514 await pause(2.5)
515 FileManager.default.createFile(atPath: dir + "/\(name).ready", contents: nil)
516 await pause(2)
517 }
518 /// Jumps (no animation needed for stills) so a section sits at the top of the screen.
519 private func jump(_ screen: String, _ anchor: TourAnchor) async {
520 tourScroll = TourScroll(screen: screen, anchor: anchor); await pause(2.8); tourScroll = nil
521 }
522
523 private func padShots(_ dir: String) async {
524 await pause(1)
525 await shot(dir, "pad-overview")
526 await jump("pad", .bottom); await shot(dir, "pad-overview-every-site")
527 for s in sites.prefix(2) { padSelection = .site(s.id); await shot(dir, "pad-site-\(s.id)") }
528 padSelection = .apps; await shot(dir, "pad-apps")
529 await jump("pad", .bottom); await shot(dir, "pad-apps-every-app")
530 for d in dashboards {
531 padSelection = .dashboard(d.id)
532 await shot(dir, "pad-dashboard-" + d.name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined())
533 }
534 padSelection = .overview
535 FileManager.default.createFile(atPath: dir + "/finished.ready", contents: nil)
536 }
537
538 private func phoneShots(_ dir: String) async {
539 func shot(_ name: String) async { await self.shot(dir, name) }
540 await pause(1)
541 await shot("today")
542 await jump("today", .section("Sites")); await shot("today-sites")
543 await jump("today", .section("Apps")); await shot("today-apps")
544 await jump("today", .bottom); await shot("today-bottom")
545 await jump("today", .top)
546 if let s = sites.first { todayPath = [s]; await shot("site-\(s.id)"); todayPath = []; await pause(0.8) }
547 tab = .dashboards; await shot("dashboards")
548 for d in dashboards {
549 dashboardsPath = [d.id]
550 let slug = d.name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined()
551 await shot("dashboard-\(slug)")
552 await jump("dashboard", .bottom); await shot("dashboard-\(slug)-bottom")
553 dashboardsPath = []; await pause(0.8)
554 }
555 tab = .sites; await shot("sites")
556 await jump("sites", .bottom); await shot("sites-bottom")
557 tab = .apps; await shot("apps")
558 await jump("apps", .bottom); await shot("apps-every-app")
559 FileManager.default.createFile(atPath: dir + "/finished.ready", contents: nil)
560 }
561
562 private func phoneTour() async {
563 await pause(1)
564 await scroll("today", hold: 3.2); await top("today")
565 if let s = sites.first { todayPath = [s]; await pause(3); await scroll("site"); todayPath = []; await pause(1.5) }
566 tab = .sites; await pause(2.5); await scroll("sites")
567 if sites.count > 1 { sitesPath = [sites[1]]; await pause(3); await scroll("site"); sitesPath = []; await pause(1.2) }
568 tab = .apps; await pause(3); await scroll("apps")
569 forcedScheme = .dark
570 tab = .today; await pause(3)
571 tab = .apps; await pause(2.5)
572 forcedScheme = nil
573 tab = .today
574 }
575}
576#endif
577
578/// Every dashboard from the Mac, one tap each; the dashboard itself draws one column.
579struct PhoneDashboardsView: View {
580 @Environment(PhoneModel.self) private var model
581 static let icons = ["overview": "square.grid.2x2", "every-site": "list.bullet.rectangle", "app-store": "arrow.down.app", "downloads": "arrow.down.circle",
582 "traffic": "point.3.connected.trianglepath.dotted", "site-detail": "cursorarrow.click.2", "search": "magnifyingglass",
583 "followers": "person.2", "ads": "megaphone"]
584 var body: some View {
585 @Bindable var model = model
586 NavigationStack(path: $model.dashboardsPath) {
587 TourScrollView("dashboards") {
588 VStack(alignment: .leading, spacing: 8) {
589 UpdatedLine()
590 if model.dashboards.isEmpty {
591 TideCard { EmptyState("No dashboards yet", message: "They come from Graphley on your Mac with the next refresh.") }
592 }
593 ForEach(model.dashboards) { d in
594 NavigationLink(value: d.id) {
595 HStack(spacing: 12) {
596 Image(systemName: Self.icons[d.id] ?? "rectangle.3.group").font(.system(size: 15, weight: .medium)).foregroundStyle(Tide.accent)
597 .frame(width: 32, height: 32).background(Tide.sunk, in: RoundedRectangle(cornerRadius: 8))
598 VStack(alignment: .leading, spacing: 2) {
599 Text(d.name).font(Tide.rowTitle).foregroundStyle(Tide.ink)
600 Text(d.widgets.map(\.title).prefix(3).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1)
601 }
602 Spacer()
603 Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Tide.muted)
604 }
605 .padding(14).background(Tide.surface, in: RoundedRectangle(cornerRadius: 14))
606 .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tide.line))
607 }
608 .buttonStyle(.plain)
609 }
610 }.padding(16)
611 }
612 .refreshable { await model.load() }
613 .background(Tide.ground)
614 .navigationTitle("Dashboards")
615 .navigationDestination(for: String.self) { id in PhoneDashboardView(dashboardID: id) }
616 }
617 }
618}
619
620struct PhoneDashboardView: View {
621 @Environment(PhoneModel.self) private var model
622 let dashboardID: String
623 var body: some View {
624 let dash = model.dashboards.first { $0.id == dashboardID }
625 TourScrollView("dashboard") {
626 if let dash { DashboardBoard(data: model.portfolio, dashboard: dash, compact: true).padding(16) }
627 }
628 .background(Tide.ground)
629 .navigationTitle(dash?.name ?? "Dashboard")
630 .navigationBarTitleDisplayMode(.inline)
631 }
632}