Graphley / app · graphley.ai / Apps / Mac / Screens.swift
| 1 | import SwiftUI |
| 2 | import AnalyticsKit |
| 3 | import AnalyticsUI |
| 4 | |
| 5 | // Data screens: Overview, a site, App Store and dashboards (design/DESIGN.md 3.4 to 3.7). |
| 6 | |
| 7 | struct OverviewView: View { |
| 8 | @Environment(AppModel.self) private var model |
| 9 | @State private var contentWidth: CGFloat = 1_000 |
| 10 | /// Below these widths the downloads card moves under the table instead of being squeezed. |
| 11 | static let siteTableMin: CGFloat = 600, downloadsMin: CGFloat = 300 |
| 12 | |
| 13 | var body: some View { |
| 14 | let n = model.range |
| 15 | VStack(alignment: .leading, spacing: 16) { |
| 16 | ScreenHeading("Overview", subtitle: subtitle) |
| 17 | if model.sites.isEmpty && model.workspace.apps.isEmpty { |
| 18 | TideCard { |
| 19 | EmptyState("Let's add your first site", message: "Sign in with Google to bring in your Google Analytics sites. Or let your agent set everything up for you.") { |
| 20 | Button("Sign In with Google…") { model.selection = .sources }.buttonStyle(.tide(.primary, size: .large)) |
| 21 | Button("Set Up with an Agent") { model.selection = .agents }.buttonStyle(.tide(.secondary, size: .large)) |
| 22 | } |
| 23 | } |
| 24 | } else if model.points.isEmpty { |
| 25 | TideCard { |
| 26 | EmptyState("Getting your numbers", message: "The first refresh takes about a minute. Charts fill in as each site arrives.") { |
| 27 | if model.refreshing { ProgressView().controlSize(.small) } |
| 28 | else { Button("Refresh Now") { Task { await model.refresh() } }.buttonStyle(.tide(.secondary)) } |
| 29 | } |
| 30 | } |
| 31 | } else { |
| 32 | HStack(spacing: 12) { |
| 33 | ForEach(tiles, id: \.0) { m, label in |
| 34 | KPITile(label, value: model.total(m, days: n), previous: model.total(m, days: n, offset: n), footer: "vs previous \(n) days") |
| 35 | } |
| 36 | } |
| 37 | TideCard("Daily visitors by site", subtitle: "Stacked. Point at a day to see each site.") { |
| 38 | StackedChart(days: model.days, series: stackedSeries).frame(height: 240) |
| 39 | } |
| 40 | let showsDownloads = !model.workspace.apps.isEmpty && model.hasAppStoreKey |
| 41 | let sideBySide = !showsDownloads || contentWidth >= Self.siteTableMin + 12 + Self.downloadsMin |
| 42 | Group { |
| 43 | if sideBySide { |
| 44 | // Both cards take the taller one's height; the downloads chart fills the difference. |
| 45 | HStack(alignment: .top, spacing: 12) { |
| 46 | siteTable(n).frame(maxWidth: .infinity, maxHeight: .infinity) |
| 47 | if showsDownloads { downloads(n, fills: true).frame(minWidth: Self.downloadsMin, maxWidth: 360, maxHeight: .infinity) } |
| 48 | } |
| 49 | .fixedSize(horizontal: false, vertical: true) |
| 50 | } else { |
| 51 | VStack(alignment: .leading, spacing: 16) { |
| 52 | siteTable(n) |
| 53 | downloads(n, fills: false) |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func siteTable(_ n: Int) -> some View { |
| 63 | TideCard("Every site", subtitle: "Last \(n) days vs the \(n) before. Click a site to open it.") { |
| 64 | SiteTable().frame(maxHeight: .infinity, alignment: .top) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// Downloads per app, then all apps' downloads per day. Beside the table the chart grows to |
| 69 | /// end level with it; stacked under the table it keeps a fixed height. |
| 70 | func downloads(_ n: Int, fills: Bool) -> some View { |
| 71 | TideCard("App Store downloads", subtitle: "First-time downloads, last \(n) days") { |
| 72 | BarList(model.workspace.apps.map { ($0.name.components(separatedBy: ":").first ?? $0.name, model.total(.appDownloads, site: $0.id, days: n)) } |
| 73 | .sorted { $0.1 > $1.1 }) |
| 74 | // Bars, not a line: daily counts are small, and a line makes a swing of one look dramatic. |
| 75 | StackedChart(days: model.days, series: [.init(id: "downloads", name: "Downloads per day, all apps", color: Tide.accent, |
| 76 | values: model.series(.appDownloads, days: model.days))], bars: true) |
| 77 | .frame(minHeight: fills ? 160 : 180, maxHeight: fills ? .infinity : 180) |
| 78 | .padding(.top, 12) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | var subtitle: String { |
| 83 | let sites = model.sites.count, apps = model.workspace.apps.count |
| 84 | var s = "\(sites) \(sites == 1 ? "site" : "sites") and \(apps) \(apps == 1 ? "app" : "apps")" |
| 85 | if let last = model.points.map(\.day).max(), let date = ISO8601DateFormatter.dayOnly.date(from: last) { |
| 86 | s += " · data through \(date.formatted(.dateTime.month(.abbreviated).day()))" |
| 87 | } |
| 88 | return s |
| 89 | } |
| 90 | |
| 91 | var tiles: [(Metric, String)] { |
| 92 | var t: [(Metric, String)] = [(.users, "Visitors"), (.sessions, "Sessions"), (.pageViews, "Page views")] |
| 93 | if model.hasAppStoreKey && !model.workspace.apps.isEmpty { t.append((.appDownloads, "App Store downloads")) } |
| 94 | return t |
| 95 | } |
| 96 | |
| 97 | /// Top five sites plus one "Other sites" band, so colors never repeat. |
| 98 | var stackedSeries: [StackedChart.Series] { |
| 99 | let ranked = model.sites.sorted { model.total(.users, site: $0.id, days: model.range) > model.total(.users, site: $1.id, days: model.range) } |
| 100 | var series = ranked.prefix(5).map { StackedChart.Series(id: $0.id, name: $0.name, color: Tide.color(for: $0), values: model.series(.users, sites: [$0.id], days: model.days)) } |
| 101 | let rest = ranked.dropFirst(5).map(\.id) |
| 102 | if !rest.isEmpty { |
| 103 | series.append(.init(id: "other", name: "Other sites", color: Tide.other, values: model.series(.users, sites: Set(rest), days: model.days))) |
| 104 | } |
| 105 | return series |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | struct SiteTable: View { |
| 110 | @Environment(AppModel.self) private var model |
| 111 | var body: some View { |
| 112 | let n = model.range |
| 113 | VStack(spacing: 0) { |
| 114 | HStack(spacing: 12) { |
| 115 | Text("Site").frame(maxWidth: .infinity, alignment: .leading) |
| 116 | Text("Trend").frame(width: 80, alignment: .leading) |
| 117 | Text("Visitors").frame(width: 70, alignment: .trailing) |
| 118 | Text("Change").frame(width: 56, alignment: .trailing) |
| 119 | Text("Page views").frame(width: 76, alignment: .trailing) |
| 120 | } |
| 121 | .font(Tide.caption).foregroundStyle(Tide.muted) |
| 122 | .padding(.horizontal, 8).padding(.bottom, 6) |
| 123 | RowDivider() |
| 124 | ForEach(model.sites.sorted { model.total(.users, site: $0.id, days: n) > model.total(.users, site: $1.id, days: n) }) { s in |
| 125 | SiteTableRow(site: s) |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | struct SiteTableRow: View { |
| 132 | let site: Site |
| 133 | @Environment(AppModel.self) private var model |
| 134 | @State private var hover = false |
| 135 | var body: some View { |
| 136 | let n = model.range |
| 137 | let cur = model.total(.users, site: site.id, days: n) |
| 138 | Button { model.selection = .site(site.id) } label: { |
| 139 | HStack(spacing: 12) { |
| 140 | HStack(spacing: 8) { |
| 141 | Circle().fill(Tide.color(for: site)).frame(width: 8, height: 8) |
| 142 | Text(site.name).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink).lineLimit(1) |
| 143 | } |
| 144 | .frame(maxWidth: .infinity, alignment: .leading) |
| 145 | Sparkline(model.series(.users, sites: [site.id], days: model.days), color: Tide.color(for: site)) |
| 146 | Text(Tide.number(cur)).font(Tide.figure(13)).foregroundStyle(Tide.ink).frame(width: 70, alignment: .trailing) |
| 147 | DeltaLabel(current: cur, previous: model.total(.users, site: site.id, days: n, offset: n)).frame(width: 56, alignment: .trailing) |
| 148 | Text(Tide.number(model.total(.pageViews, site: site.id, days: n))).font(Tide.figure(13)).foregroundStyle(Tide.ink2).frame(width: 76, alignment: .trailing) |
| 149 | } |
| 150 | .padding(.horizontal, 8).frame(height: 32) |
| 151 | .background(hover ? Tide.sunk : .clear, in: RoundedRectangle(cornerRadius: 6)) |
| 152 | .contentShape(Rectangle()) |
| 153 | } |
| 154 | .buttonStyle(.plain) |
| 155 | .onHover { hover = $0 } |
| 156 | .help("Open \(site.name)") |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | struct SiteView: View { |
| 161 | @Environment(AppModel.self) private var model |
| 162 | let siteID: String |
| 163 | @State private var metric: Metric = .users |
| 164 | |
| 165 | static let eventNames = ["mac_installer_download": "Mac downloads", "download_click_mac": "Mac downloads", |
| 166 | "app_store_click": "App Store clicks", "download_click_ios": "App Store clicks", |
| 167 | "source_click": "Source clicks", "source_download": "Source downloads", |
| 168 | "newsletter_click": "Newsletter clicks", "book_call": "Calls booked", "generate_lead": "Leads"] |
| 169 | |
| 170 | var body: some View { |
| 171 | if let site = model.sites.first(where: { $0.id == siteID }) { |
| 172 | let n = model.range |
| 173 | let pages = model.points.filter { $0.subject == siteID && ($0.breakdown?.hasPrefix("page:") ?? false) } |
| 174 | .sorted { $0.value > $1.value }.prefix(10).map { (String($0.breakdown!.dropFirst(5)), $0.value) } |
| 175 | VStack(alignment: .leading, spacing: 16) { |
| 176 | ScreenHeading(site.name, subtitle: "Google Analytics 4", |
| 177 | link: site.url.map { (title: $0.host() ?? site.name, url: $0) }) |
| 178 | HStack(spacing: 12) { |
| 179 | ForEach([Metric.users, .newUsers, .sessions, .pageViews], id: \.self) { m in |
| 180 | Button { withAnimation(.easeOut(duration: 0.15)) { metric = m } } label: { |
| 181 | KPITile(m.title, value: model.total(m, site: siteID, days: n), previous: model.total(m, site: siteID, days: n, offset: n), |
| 182 | footer: "vs previous \(n) days", selected: metric == m) |
| 183 | } |
| 184 | .buttonStyle(.plain) |
| 185 | } |
| 186 | } |
| 187 | HStack(alignment: .top, spacing: 16) { |
| 188 | TideCard("\(metric.title) per day") { |
| 189 | let values = model.series(metric, sites: [siteID], days: model.days) |
| 190 | TrendChart(days: model.days, values: values, color: Tide.color(for: site), label: metric.title).frame(height: 240) |
| 191 | if values.allSatisfy({ $0 == 0 }) { |
| 192 | Text("No \(metric.title.lowercased()) in the last \(n) days.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 193 | } |
| 194 | } |
| 195 | .layoutPriority(1) |
| 196 | TideCard("Top pages", subtitle: "Page views, last 30 days") { |
| 197 | if pages.isEmpty { Text("No page views recorded yet.").font(Tide.secondary).foregroundStyle(Tide.muted) } |
| 198 | else { BarList(Array(pages)) } |
| 199 | } |
| 200 | .frame(width: 320) |
| 201 | } |
| 202 | let events = keyEvents(n) |
| 203 | if !events.isEmpty { |
| 204 | TideCard("Key events", subtitle: "Last \(n) days") { BarList(events) } |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func keyEvents(_ n: Int) -> [(String, Double)] { |
| 211 | let days = Set(DayKey.lastDays(n)) |
| 212 | var totals: [String: Double] = [:] |
| 213 | for p in model.points where p.subject == siteID && p.metric == .keyEvent && days.contains(p.day) { |
| 214 | guard let e = p.event else { continue } |
| 215 | totals[Self.eventNames[e] ?? e, default: 0] += p.value |
| 216 | } |
| 217 | return totals.filter { $0.value > 0 }.sorted { $0.value > $1.value }.map { ($0.key, $0.value) } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | struct AppStoreView: View { |
| 222 | @Environment(AppModel.self) private var model |
| 223 | |
| 224 | static func platformName(_ raw: String) -> String { |
| 225 | let p = raw.hasPrefix("platform:") ? String(raw.dropFirst(9)) : raw |
| 226 | switch p.lowercased() { |
| 227 | case "iphone": return "iPhone" |
| 228 | case "ipad": return "iPad" |
| 229 | case "desktop", "mac": return "Mac" |
| 230 | case "apple vision", "vision", "apple vision pro": return "Apple Vision Pro" |
| 231 | case "apple tv", "appletv": return "Apple TV" |
| 232 | default: return p |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | var body: some View { |
| 237 | let n = model.range |
| 238 | let platforms = Set(model.points.filter { $0.metric == .appDownloads }.compactMap(\.breakdown)).sorted() |
| 239 | VStack(alignment: .leading, spacing: 16) { |
| 240 | ScreenHeading("Apps", subtitle: "App Store downloads from App Store Connect, and Mac installers from each app's website.") |
| 241 | // Downloads already in the store (refreshed on another Mac, key not synced here yet) still show. |
| 242 | if !model.hasAppStoreKey && !model.points.contains(where: { $0.metric == .appDownloads }) { |
| 243 | TideCard { |
| 244 | EmptyState("Connect App Store Connect", message: "Add an API key to see daily downloads for your apps. It takes about two minutes in App Store Connect.") { |
| 245 | Button("Add App Store Key") { model.selection = .sources }.buttonStyle(.tide(.primary, size: .large)) |
| 246 | } |
| 247 | } |
| 248 | } else if model.workspace.apps.isEmpty { |
| 249 | TideCard { |
| 250 | EmptyState("No apps yet", message: "Ask your agent to “add my App Store apps to Graphley”, and they'll show up here after the next refresh.") { |
| 251 | PromptChip("Add my App Store apps to Graphley and refresh.") |
| 252 | } |
| 253 | } |
| 254 | } else { |
| 255 | HStack(spacing: 12) { |
| 256 | ForEach(model.workspace.apps.filter(\.hasAppStoreListing)) { app in |
| 257 | KPITile(app.shortName, value: model.total(.appDownloads, site: app.id, days: n), |
| 258 | previous: model.total(.appDownloads, site: app.id, days: n, offset: n), footer: "vs previous \(n) days") |
| 259 | } |
| 260 | } |
| 261 | TideCard("Downloads per day by platform", subtitle: "All apps") { |
| 262 | StackedChart(days: model.days, series: platforms.enumerated().map { i, p in |
| 263 | let byDay = Dictionary(grouping: model.points.filter { $0.metric == .appDownloads && $0.breakdown == p }, by: \.day).mapValues { $0.reduce(0) { $0 + $1.value } } |
| 264 | return .init(id: p, name: Self.platformName(p), color: Tide.series[i % Tide.series.count], values: model.days.map { byDay[$0] ?? 0 }) |
| 265 | }, bars: true).frame(height: 240) |
| 266 | } |
| 267 | TideCard("Every app", subtitle: "Last \(n) days") { |
| 268 | Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) { |
| 269 | GridRow { |
| 270 | Text("App"); Text("App Store").gridColumnAlignment(.trailing); Text("Mac (website)").gridColumnAlignment(.trailing) |
| 271 | Text("Redownloads").gridColumnAlignment(.trailing); Text("Rating").gridColumnAlignment(.trailing) |
| 272 | } |
| 273 | .font(Tide.caption).foregroundStyle(Tide.muted) |
| 274 | // Every app, including Mac apps that are only downloaded from their website. |
| 275 | ForEach(model.workspace.apps) { app in |
| 276 | GridRow { |
| 277 | VStack(alignment: .leading, spacing: 1) { |
| 278 | Text(app.shortName).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink) |
| 279 | Text((app.platforms ?? []).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted) |
| 280 | } |
| 281 | Text(app.hasAppStoreListing ? Tide.number(model.total(.appDownloads, site: app.id, days: n)) : "–").font(Tide.figure(13)) |
| 282 | Text(model.points.websiteDownloads(app, days: model.days).map { Tide.number($0.reduce(0, +)) } ?? "–").font(Tide.figure(13)) |
| 283 | Text(app.hasAppStoreListing ? Tide.number(model.total(.appRedownloads, site: app.id, days: n)) : "–").font(Tide.figure(13)).foregroundStyle(Tide.ink2) |
| 284 | Text(rating(app.id)).font(Tide.figure(13)).foregroundStyle(Tide.ink2) |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | func rating(_ id: String) -> String { |
| 294 | guard let r = model.points.filter({ $0.subject == id && $0.metric == .rating && $0.breakdown == nil }).max(by: { $0.day < $1.day }), r.value > 0 else { return "–" } |
| 295 | return r.value.formatted(.number.precision(.fractionLength(1))) + " ★" |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | struct DashboardView: View { |
| 300 | @Environment(AppModel.self) private var model |
| 301 | let dashboardID: String |
| 302 | static let prompt = "Add a chart of my top site's visitors to my dashboard" |
| 303 | var body: some View { |
| 304 | if let dash = model.workspace.dashboards.first(where: { $0.id == dashboardID }) { |
| 305 | VStack(alignment: .leading, spacing: 16) { |
| 306 | ScreenHeading(dash.name, subtitle: "Ask your agent to add or change widgets.", trailing: { EmptyView() }, footnote: { |
| 307 | if !dash.widgets.isEmpty { PromptLine(Self.prompt) } |
| 308 | }) |
| 309 | if dash.widgets.isEmpty { |
| 310 | TideCard { |
| 311 | EmptyState("This dashboard is empty", message: "Ask your agent to add widgets, for example “\(Self.prompt.lowercased())”.") { |
| 312 | CopyButton(Self.prompt, label: "Copy Prompt") |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | DashboardBoard(data: model.portfolio, dashboard: dash) |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | extension ISO8601DateFormatter { |
| 323 | nonisolated(unsafe) static let dayOnly: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }() |
| 324 | } |