import SwiftUI import AnalyticsKit import AnalyticsUI // Data screens: Overview, a site, App Store and dashboards (design/DESIGN.md 3.4 to 3.7). struct OverviewView: View { @Environment(AppModel.self) private var model @State private var contentWidth: CGFloat = 1_000 /// Below these widths the downloads card moves under the table instead of being squeezed. static let siteTableMin: CGFloat = 600, downloadsMin: CGFloat = 300 var body: some View { let n = model.range VStack(alignment: .leading, spacing: 16) { ScreenHeading("Overview", subtitle: subtitle) if model.sites.isEmpty && model.workspace.apps.isEmpty { TideCard { 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.") { Button("Sign In with Google…") { model.selection = .sources }.buttonStyle(.tide(.primary, size: .large)) Button("Set Up with an Agent") { model.selection = .agents }.buttonStyle(.tide(.secondary, size: .large)) } } } else if model.points.isEmpty { TideCard { EmptyState("Getting your numbers", message: "The first refresh takes about a minute. Charts fill in as each site arrives.") { if model.refreshing { ProgressView().controlSize(.small) } else { Button("Refresh Now") { Task { await model.refresh() } }.buttonStyle(.tide(.secondary)) } } } } else { HStack(spacing: 12) { ForEach(tiles, id: \.0) { m, label in KPITile(label, value: model.total(m, days: n), previous: model.total(m, days: n, offset: n), footer: "vs previous \(n) days") } } TideCard("Daily visitors by site", subtitle: "Stacked. Point at a day to see each site.") { StackedChart(days: model.days, series: stackedSeries).frame(height: 240) } let showsDownloads = !model.workspace.apps.isEmpty && model.hasAppStoreKey let sideBySide = !showsDownloads || contentWidth >= Self.siteTableMin + 12 + Self.downloadsMin Group { if sideBySide { // Both cards take the taller one's height; the downloads chart fills the difference. HStack(alignment: .top, spacing: 12) { siteTable(n).frame(maxWidth: .infinity, maxHeight: .infinity) if showsDownloads { downloads(n, fills: true).frame(minWidth: Self.downloadsMin, maxWidth: 360, maxHeight: .infinity) } } .fixedSize(horizontal: false, vertical: true) } else { VStack(alignment: .leading, spacing: 16) { siteTable(n) downloads(n, fills: false) } } } .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } } } } func siteTable(_ n: Int) -> some View { TideCard("Every site", subtitle: "Last \(n) days vs the \(n) before. Click a site to open it.") { SiteTable().frame(maxHeight: .infinity, alignment: .top) } } /// Downloads per app, then all apps' downloads per day. Beside the table the chart grows to /// end level with it; stacked under the table it keeps a fixed height. func downloads(_ n: Int, fills: Bool) -> some View { TideCard("App Store downloads", subtitle: "First-time downloads, last \(n) days") { BarList(model.workspace.apps.map { ($0.name.components(separatedBy: ":").first ?? $0.name, model.total(.appDownloads, site: $0.id, days: n)) } .sorted { $0.1 > $1.1 }) // Bars, not a line: daily counts are small, and a line makes a swing of one look dramatic. StackedChart(days: model.days, series: [.init(id: "downloads", name: "Downloads per day, all apps", color: Tide.accent, values: model.series(.appDownloads, days: model.days))], bars: true) .frame(minHeight: fills ? 160 : 180, maxHeight: fills ? .infinity : 180) .padding(.top, 12) } } var subtitle: String { let sites = model.sites.count, apps = model.workspace.apps.count var s = "\(sites) \(sites == 1 ? "site" : "sites") and \(apps) \(apps == 1 ? "app" : "apps")" if let last = model.points.map(\.day).max(), let date = ISO8601DateFormatter.dayOnly.date(from: last) { s += " · data through \(date.formatted(.dateTime.month(.abbreviated).day()))" } return s } var tiles: [(Metric, String)] { var t: [(Metric, String)] = [(.users, "Visitors"), (.sessions, "Sessions"), (.pageViews, "Page views")] if model.hasAppStoreKey && !model.workspace.apps.isEmpty { t.append((.appDownloads, "App Store downloads")) } return t } /// Top five sites plus one "Other sites" band, so colors never repeat. var stackedSeries: [StackedChart.Series] { let ranked = model.sites.sorted { model.total(.users, site: $0.id, days: model.range) > model.total(.users, site: $1.id, days: model.range) } 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)) } let rest = ranked.dropFirst(5).map(\.id) if !rest.isEmpty { series.append(.init(id: "other", name: "Other sites", color: Tide.other, values: model.series(.users, sites: Set(rest), days: model.days))) } return series } } struct SiteTable: View { @Environment(AppModel.self) private var model var body: some View { let n = model.range VStack(spacing: 0) { HStack(spacing: 12) { Text("Site").frame(maxWidth: .infinity, alignment: .leading) Text("Trend").frame(width: 80, alignment: .leading) Text("Visitors").frame(width: 70, alignment: .trailing) Text("Change").frame(width: 56, alignment: .trailing) Text("Page views").frame(width: 76, alignment: .trailing) } .font(Tide.caption).foregroundStyle(Tide.muted) .padding(.horizontal, 8).padding(.bottom, 6) RowDivider() ForEach(model.sites.sorted { model.total(.users, site: $0.id, days: n) > model.total(.users, site: $1.id, days: n) }) { s in SiteTableRow(site: s) } } } } struct SiteTableRow: View { let site: Site @Environment(AppModel.self) private var model @State private var hover = false var body: some View { let n = model.range let cur = model.total(.users, site: site.id, days: n) Button { model.selection = .site(site.id) } label: { HStack(spacing: 12) { HStack(spacing: 8) { Circle().fill(Tide.color(for: site)).frame(width: 8, height: 8) Text(site.name).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink).lineLimit(1) } .frame(maxWidth: .infinity, alignment: .leading) Sparkline(model.series(.users, sites: [site.id], days: model.days), color: Tide.color(for: site)) Text(Tide.number(cur)).font(Tide.figure(13)).foregroundStyle(Tide.ink).frame(width: 70, alignment: .trailing) DeltaLabel(current: cur, previous: model.total(.users, site: site.id, days: n, offset: n)).frame(width: 56, alignment: .trailing) Text(Tide.number(model.total(.pageViews, site: site.id, days: n))).font(Tide.figure(13)).foregroundStyle(Tide.ink2).frame(width: 76, alignment: .trailing) } .padding(.horizontal, 8).frame(height: 32) .background(hover ? Tide.sunk : .clear, in: RoundedRectangle(cornerRadius: 6)) .contentShape(Rectangle()) } .buttonStyle(.plain) .onHover { hover = $0 } .help("Open \(site.name)") } } struct SiteView: View { @Environment(AppModel.self) private var model let siteID: String @State private var metric: Metric = .users static let eventNames = ["mac_installer_download": "Mac downloads", "download_click_mac": "Mac downloads", "app_store_click": "App Store clicks", "download_click_ios": "App Store clicks", "source_click": "Source clicks", "source_download": "Source downloads", "newsletter_click": "Newsletter clicks", "book_call": "Calls booked", "generate_lead": "Leads"] var body: some View { if let site = model.sites.first(where: { $0.id == siteID }) { let n = model.range let pages = model.points.filter { $0.subject == siteID && ($0.breakdown?.hasPrefix("page:") ?? false) } .sorted { $0.value > $1.value }.prefix(10).map { (String($0.breakdown!.dropFirst(5)), $0.value) } VStack(alignment: .leading, spacing: 16) { ScreenHeading(site.name, subtitle: "Google Analytics 4", link: site.url.map { (title: $0.host() ?? site.name, url: $0) }) HStack(spacing: 12) { ForEach([Metric.users, .newUsers, .sessions, .pageViews], id: \.self) { m in Button { withAnimation(.easeOut(duration: 0.15)) { metric = m } } label: { KPITile(m.title, value: model.total(m, site: siteID, days: n), previous: model.total(m, site: siteID, days: n, offset: n), footer: "vs previous \(n) days", selected: metric == m) } .buttonStyle(.plain) } } HStack(alignment: .top, spacing: 16) { TideCard("\(metric.title) per day") { let values = model.series(metric, sites: [siteID], days: model.days) TrendChart(days: model.days, values: values, color: Tide.color(for: site), label: metric.title).frame(height: 240) if values.allSatisfy({ $0 == 0 }) { Text("No \(metric.title.lowercased()) in the last \(n) days.").font(Tide.secondary).foregroundStyle(Tide.muted) } } .layoutPriority(1) TideCard("Top pages", subtitle: "Page views, last 30 days") { if pages.isEmpty { Text("No page views recorded yet.").font(Tide.secondary).foregroundStyle(Tide.muted) } else { BarList(Array(pages)) } } .frame(width: 320) } let events = keyEvents(n) if !events.isEmpty { TideCard("Key events", subtitle: "Last \(n) days") { BarList(events) } } } } } func keyEvents(_ n: Int) -> [(String, Double)] { let days = Set(DayKey.lastDays(n)) var totals: [String: Double] = [:] for p in model.points where p.subject == siteID && p.metric == .keyEvent && days.contains(p.day) { guard let e = p.event else { continue } totals[Self.eventNames[e] ?? e, default: 0] += p.value } return totals.filter { $0.value > 0 }.sorted { $0.value > $1.value }.map { ($0.key, $0.value) } } } struct AppStoreView: View { @Environment(AppModel.self) private var model static func platformName(_ raw: String) -> String { let p = raw.hasPrefix("platform:") ? String(raw.dropFirst(9)) : raw switch p.lowercased() { case "iphone": return "iPhone" case "ipad": return "iPad" case "desktop", "mac": return "Mac" case "apple vision", "vision", "apple vision pro": return "Apple Vision Pro" case "apple tv", "appletv": return "Apple TV" default: return p } } var body: some View { let n = model.range let platforms = Set(model.points.filter { $0.metric == .appDownloads }.compactMap(\.breakdown)).sorted() VStack(alignment: .leading, spacing: 16) { ScreenHeading("Apps", subtitle: "App Store downloads from App Store Connect, and Mac installers from each app's website.") // Downloads already in the store (refreshed on another Mac, key not synced here yet) still show. if !model.hasAppStoreKey && !model.points.contains(where: { $0.metric == .appDownloads }) { TideCard { 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.") { Button("Add App Store Key") { model.selection = .sources }.buttonStyle(.tide(.primary, size: .large)) } } } else if model.workspace.apps.isEmpty { TideCard { 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.") { PromptChip("Add my App Store apps to Graphley and refresh.") } } } else { HStack(spacing: 12) { ForEach(model.workspace.apps.filter(\.hasAppStoreListing)) { app in KPITile(app.shortName, value: model.total(.appDownloads, site: app.id, days: n), previous: model.total(.appDownloads, site: app.id, days: n, offset: n), footer: "vs previous \(n) days") } } TideCard("Downloads per day by platform", subtitle: "All apps") { StackedChart(days: model.days, series: platforms.enumerated().map { i, p in let byDay = Dictionary(grouping: model.points.filter { $0.metric == .appDownloads && $0.breakdown == p }, by: \.day).mapValues { $0.reduce(0) { $0 + $1.value } } return .init(id: p, name: Self.platformName(p), color: Tide.series[i % Tide.series.count], values: model.days.map { byDay[$0] ?? 0 }) }, bars: true).frame(height: 240) } TideCard("Every app", subtitle: "Last \(n) days") { Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) { GridRow { Text("App"); Text("App Store").gridColumnAlignment(.trailing); Text("Mac (website)").gridColumnAlignment(.trailing) Text("Redownloads").gridColumnAlignment(.trailing); Text("Rating").gridColumnAlignment(.trailing) } .font(Tide.caption).foregroundStyle(Tide.muted) // Every app, including Mac apps that are only downloaded from their website. ForEach(model.workspace.apps) { app in GridRow { VStack(alignment: .leading, spacing: 1) { Text(app.shortName).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink) Text((app.platforms ?? []).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted) } Text(app.hasAppStoreListing ? Tide.number(model.total(.appDownloads, site: app.id, days: n)) : "–").font(Tide.figure(13)) Text(model.points.websiteDownloads(app, days: model.days).map { Tide.number($0.reduce(0, +)) } ?? "–").font(Tide.figure(13)) Text(app.hasAppStoreListing ? Tide.number(model.total(.appRedownloads, site: app.id, days: n)) : "–").font(Tide.figure(13)).foregroundStyle(Tide.ink2) Text(rating(app.id)).font(Tide.figure(13)).foregroundStyle(Tide.ink2) } } } } } } } func rating(_ id: String) -> String { 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 "–" } return r.value.formatted(.number.precision(.fractionLength(1))) + " ★" } } struct DashboardView: View { @Environment(AppModel.self) private var model let dashboardID: String static let prompt = "Add a chart of my top site's visitors to my dashboard" var body: some View { if let dash = model.workspace.dashboards.first(where: { $0.id == dashboardID }) { VStack(alignment: .leading, spacing: 16) { ScreenHeading(dash.name, subtitle: "Ask your agent to add or change widgets.", trailing: { EmptyView() }, footnote: { if !dash.widgets.isEmpty { PromptLine(Self.prompt) } }) if dash.widgets.isEmpty { TideCard { EmptyState("This dashboard is empty", message: "Ask your agent to add widgets, for example “\(Self.prompt.lowercased())”.") { CopyButton(Self.prompt, label: "Copy Prompt") } } } DashboardBoard(data: model.portfolio, dashboard: dash) } } } } extension ISO8601DateFormatter { nonisolated(unsafe) static let dayOnly: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }() }