import SwiftUI import AnalyticsKit import AnalyticsUI // iPad: the Mac's layout for reading. Our own sidebar rows on the left, one screen on the right, // the same Tide cards, tiles and charts as the Mac (design/DESIGN.md). Everything here is // read-only; the Mac refreshes the numbers and shares them through iCloud. enum PadItem: Hashable { case overview, apps, dashboard(String), site(String), settings } struct PadRootView: View { @Environment(PhoneModel.self) private var model @State private var columns: NavigationSplitViewVisibility = .all var body: some View { NavigationSplitView(columnVisibility: $columns) { PadSidebar() .navigationSplitViewColumnWidth(min: 260, ideal: 290, max: 340) .toolbar(.hidden, for: .navigationBar) } detail: { PadDetail() } .navigationSplitViewStyle(.balanced) } } // MARK: Sidebar struct PadSidebar: View { @Environment(PhoneModel.self) private var model var body: some View { VStack(alignment: .leading, spacing: 0) { HStack(spacing: 10) { TideMark(size: 30) Text("Graphley").font(Tide.display(22)).tracking(-0.3).foregroundStyle(Tide.ink) } .padding(.horizontal, 22).padding(.top, 20).padding(.bottom, 6) .accessibilityElement(children: .combine) ScrollView { VStack(alignment: .leading, spacing: 2) { PadSectionLabel("Portfolio") PadSidebarRow("Overview", icon: "chart.xyaxis.line", item: .overview) PadSidebarRow("Apps", icon: "arrow.down.app", item: .apps) ForEach(model.dashboards) { d in PadSidebarRow(d.name, icon: "rectangle.3.group", item: .dashboard(d.id)) } if !model.sites.isEmpty { PadSectionLabel("Sites") // Same order as the Mac's sidebar, which the user sets by dragging there. ForEach(model.sites) { site in PadSidebarRow(site.name, dot: Tide.color(for: site), count: model.total(.users, [site.id], days: model.range), item: .site(site.id)) } } PadSectionLabel("Graphley") PadSidebarRow("Settings", icon: "gearshape", item: .settings) } .padding(.horizontal, 12).padding(.bottom, 12) } PadSyncStatus() } .background(Tide.ground) } } struct PadSectionLabel: View { let text: String init(_ text: String) { self.text = text } var body: some View { Text(text.uppercased()).font(Tide.sectionLabel).tracking(0.8).foregroundStyle(Tide.muted) .padding(.leading, 12).padding(.top, 18).padding(.bottom, 6) .accessibilityAddTraits(.isHeader) } } struct PadSidebarRow: View { let title: String, icon: String?, dot: Color?, count: Double?, item: PadItem @Environment(PhoneModel.self) private var model @Environment(\.colorScheme) private var scheme @State private var hover = false init(_ title: String, icon: String? = nil, dot: Color? = nil, count: Double? = nil, item: PadItem) { self.title = title; self.icon = icon; self.dot = dot; self.count = count; self.item = item } var body: some View { let selected = model.padSelection == item Button { model.padSelection = item } label: { HStack(spacing: 10) { if let icon { Image(systemName: icon).font(.system(size: 16, weight: .medium)).frame(width: 22) .foregroundStyle(selected ? Tide.accentInk : Tide.muted) } else if let dot { // On the selected row the dot turns light, so a teal site stays visible on the teal fill. Circle().fill(selected ? Tide.accentInk : dot).frame(width: 9, height: 9).frame(width: 22) } Text(title).font(Tide.sans(16, .medium)).lineLimit(1).truncationMode(.tail) .foregroundStyle(selected ? Tide.accentInk : Tide.ink) Spacer(minLength: 4) if let count { Text(Tide.number(count)).font(Tide.figure(13)) .foregroundStyle(selected ? Tide.accentInk.opacity(0.75) : Tide.muted) } } .padding(.horizontal, 12) .frame(height: 44) .background(selected ? Tide.fill : hover ? (scheme == .dark ? Tide.surface2 : Tide.sunk) : .clear, in: RoundedRectangle(cornerRadius: 10)) .contentShape(RoundedRectangle(cornerRadius: 10)) } .buttonStyle(.plain) .onHover { hover = $0 } .accessibilityAddTraits(selected ? .isSelected : []) } } /// Bottom of the sidebar: when the Mac last shared numbers, with a button to check iCloud again. struct PadSyncStatus: View { @Environment(PhoneModel.self) private var model var body: some View { HStack(spacing: 10) { Circle().fill(dotColor).frame(width: 7, height: 7) VStack(alignment: .leading, spacing: 2) { Text(headline).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink).lineLimit(1) Text(detail).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(2) } Spacer(minLength: 4) Button { Task { await model.load() } } label: { if model.loading { ProgressView() } else { Label("Check iCloud", systemImage: "arrow.clockwise") } } .buttonStyle(.tideIcon) .disabled(model.loading) .accessibilityLabel("Check iCloud for new numbers") } .padding(.leading, 18).padding(.trailing, 10).padding(.vertical, 12) .overlay(alignment: .top) { Rectangle().fill(Tide.line).frame(height: 1) } } var stale: Bool { model.snapshot.map { Date.now.timeIntervalSince($0.refreshedAt) > 36 * 3600 } ?? false } var dotColor: Color { model.error != nil ? Tide.down : stale || model.snapshot == nil ? Tide.attention : Tide.up } var headline: String { model.snapshot == nil ? "Waiting for your Mac" : "Synced from your Mac" } var detail: String { if model.snapshot == nil, let e = model.cloud.error { return e } guard let s = model.snapshot else { return "Through iCloud" } return "Updated \(s.refreshedAt.formatted(.relative(presentation: .named)))" } } // MARK: Detail struct PadDetail: View { @Environment(PhoneModel.self) private var model var body: some View { NavigationStack { TourScrollView("pad") { VStack(alignment: .leading, spacing: 16) { if model.snapshot != nil, let e = model.error { Banner(text: e, kind: .error) } if let s = model.snapshot, Date.now.timeIntervalSince(s.refreshedAt) > 36 * 3600 { Banner(text: "These numbers are from \(s.refreshedAt.formatted(.relative(presentation: .named))). Open Graphley on your Mac to refresh.", kind: .attention) } if model.snapshot == nil && model.padSelection != .settings { PadWaiting() } else { screen } } .padding(.horizontal, 32).padding(.top, 8).padding(.bottom, 32) .frame(maxWidth: 1180, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading) } .id(model.padSelection) .refreshable { await model.load() } .background(Tide.surface) .toolbarBackground(.hidden, for: .navigationBar) .navigationBarTitleDisplayMode(.inline) } } @ViewBuilder var screen: some View { switch model.padSelection { case .overview: PadOverview() case .apps: PadAppStore() case .dashboard(let id): PadDashboard(dashboardID: id) case .site(let id): PadSite(siteID: id) case .settings: SyncSettingsContent() } } } struct PadWaiting: View { @Environment(PhoneModel.self) private var model var body: some View { ConnectMacGuide { model.padSelection = .settings } .frame(maxWidth: .infinity).padding(.top, 48) } } /// The 7 / 30 / 90 day pill, bound to the iPad's range. struct PadRange: View { @Environment(PhoneModel.self) private var model var body: some View { @Bindable var model = model RangeSelector(selection: $model.range) } } /// Lays out side by side when there is room, stacked otherwise (portrait, split view). struct PadPair: View { let wide: Bool, secondWidth: CGFloat let first: First, second: Second init(wide: Bool, secondWidth: CGFloat = 340, @ViewBuilder first: () -> First, @ViewBuilder second: () -> Second) { self.wide = wide; self.secondWidth = secondWidth; self.first = first(); self.second = second() } var body: some View { if wide { HStack(alignment: .top, spacing: 16) { first.layoutPriority(1); second.frame(width: secondWidth) } } else { VStack(alignment: .leading, spacing: 16) { first; second } } } } /// Measures the screen's width so cards can sit side by side in landscape. struct WidthReader: ViewModifier { @Binding var width: CGFloat func body(content: Content) -> some View { content.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 } } } // MARK: Overview struct PadOverview: View { @Environment(PhoneModel.self) private var model @State private var width: CGFloat = 900 var body: some View { let n = model.range VStack(alignment: .leading, spacing: 16) { ScreenHeading("Overview", subtitle: subtitle) { PadRange() } LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: width > 760 ? tiles.count : 2), 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. Touch a day to read it.") { StackedChart(days: model.days, series: stackedSeries).frame(height: 340) } PadPair(wide: width > 860 && !model.apps.isEmpty) { TideCard("Every site", subtitle: "Last \(n) days vs the \(n) before. Tap a site to open it.") { PadSiteTable() } } second: { if !model.apps.isEmpty { TideCard("Every app", subtitle: "App Store and Mac website downloads, last \(n) days. Tap an app to open Apps.") { Button { model.padSelection = .apps } label: { BarList(model.apps.map { ($0.shortName, model.appTotal($0, days: n)) }.sorted { $0.1 > $1.1 }) } .buttonStyle(.plain) .accessibilityHint("Opens Apps") } } } } .modifier(WidthReader(width: $width)) } var subtitle: String { let sites = model.sites.count, apps = model.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 = PadDay.date(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.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 n = model.range let ranked = model.sites.sorted { model.total(.users, [$0.id], days: n) > model.total(.users, [$1.id], days: n) } var series = ranked.prefix(5).map { StackedChart.Series(id: $0.id, name: $0.name, color: Tide.color(for: $0), values: model.series(.users, [$0.id], days: n)) } 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, Set(rest), days: n))) } return series } } struct PadSiteTable: View { @Environment(PhoneModel.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: 72, alignment: .trailing) Text("Change").frame(width: 60, alignment: .trailing) Text("Page views").frame(width: 84, alignment: .trailing) } .font(Tide.caption).foregroundStyle(Tide.muted) .padding(.horizontal, 10).padding(.bottom, 8) RowDivider() ForEach(model.sites.sorted { model.total(.users, [$0.id], days: n) > model.total(.users, [$1.id], days: n) }) { s in PadSiteRow(site: s) } } } } struct PadSiteRow: View { let site: Site @Environment(PhoneModel.self) private var model @State private var hover = false var body: some View { let n = model.range let cur = model.total(.users, [site.id], days: n) Button { model.padSelection = .site(site.id) } label: { HStack(spacing: 12) { HStack(spacing: 9) { Circle().fill(Tide.color(for: site)).frame(width: 9, height: 9) Text(site.name).font(Tide.sans(15, .medium)).foregroundStyle(Tide.ink).lineLimit(1) } .frame(maxWidth: .infinity, alignment: .leading) Sparkline(model.series(.users, [site.id], days: n), color: Tide.color(for: site)) Text(Tide.number(cur)).font(Tide.figure(14)).foregroundStyle(Tide.ink).frame(width: 72, alignment: .trailing) DeltaLabel(current: cur, previous: model.total(.users, [site.id], days: n, offset: n)).frame(width: 60, alignment: .trailing) Text(Tide.number(model.total(.pageViews, [site.id], days: n))).font(Tide.figure(14)).foregroundStyle(Tide.ink2).frame(width: 84, alignment: .trailing) } .padding(.horizontal, 10).frame(height: 46) .background(hover ? Tide.sunk : .clear, in: RoundedRectangle(cornerRadius: 8)) .contentShape(Rectangle()) } .buttonStyle(.plain) .onHover { hover = $0 } .accessibilityLabel("\(site.name), \(Tide.number(cur)) visitors") .accessibilityHint("Opens the site") } } // MARK: Site struct PadSite: View { @Environment(PhoneModel.self) private var model @Environment(\.openURL) private var openURL let siteID: String @State private var metric: Metric = .users @State private var width: CGFloat = 900 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(8).map { (String($0.breakdown!.dropFirst(5)), $0.value) } VStack(alignment: .leading, spacing: 16) { ScreenHeading(site.name, subtitle: site.url?.host() ?? "Google Analytics 4") { HStack(spacing: 6) { if let url = site.url { Button { openURL(url) } label: { Label("Open \(url.host() ?? site.name)", systemImage: "arrow.up.right.square") } .buttonStyle(.tideIcon) .accessibilityLabel("Open \(url.host() ?? site.name)") } PadRange() } } LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: width > 760 ? 4 : 2), 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, [siteID], days: n), previous: model.total(m, [siteID], days: n, offset: n), footer: "vs previous \(n) days", selected: metric == m) } .buttonStyle(.plain) } } PadPair(wide: width > 860) { TideCard("\(metric.title) per day", subtitle: "Tap a number above to switch.") { let values = model.series(metric, [siteID], days: n) TrendChart(days: model.days, values: values, color: Tide.color(for: site), label: metric.title).frame(height: 360) if values.allSatisfy({ $0 == 0 }) { Text("No \(metric.title.lowercased()) in the last \(n) days.").font(Tide.secondary).foregroundStyle(Tide.muted) } } } second: { 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)) } } } let events = keyEvents(n) if !events.isEmpty { TideCard("Key events", subtitle: "Last \(n) days") { BarList(events) } } } .modifier(WidthReader(width: $width)) } } 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) } } } // MARK: App Store struct PadAppStore: View { @Environment(PhoneModel.self) private var model @State private var width: CGFloat = 900 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.") { PadRange() } if model.apps.isEmpty { TideCard { EmptyState("No App Store numbers yet", message: "Add your App Store Connect key in Graphley on your Mac. Downloads appear here after the next refresh.") } } else { LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: min(model.apps.count, width > 760 ? 4 : 2)), spacing: 12) { ForEach(model.apps) { app in KPITile(app.shortName, value: model.appTotal(app, days: n), previous: model.appTotal(app, 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: 380) } TideCard("Every app", subtitle: "Last \(n) days") { Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 12) { 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) ForEach(model.apps) { app in let store = app.hasAppStoreListing ? model.total(.appDownloads, [app.id], days: n) : nil GridRow { VStack(alignment: .leading, spacing: 2) { Text(app.shortName).font(Tide.sans(15, .medium)).foregroundStyle(Tide.ink) Text((app.platforms ?? []).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1) } .frame(maxWidth: .infinity, alignment: .leading) Text(store.map(Tide.number) ?? "–").font(Tide.figure(14)).foregroundStyle(Tide.ink) Text(website(app, n).map(Tide.number) ?? "–").font(Tide.figure(14)).foregroundStyle(Tide.ink) Text(app.hasAppStoreListing ? Tide.number(model.total(.appRedownloads, [app.id], days: n)) : "–").font(Tide.figure(14)).foregroundStyle(Tide.ink2) Text(rating(app.id)).font(Tide.figure(14)).foregroundStyle(Tide.ink2) } } } } } } .modifier(WidthReader(width: $width)) } /// Mac installer downloads from the app's website, or nil when it has no website download. func website(_ app: StoreApp, _ n: Int) -> Double? { model.points.websiteDownloads(app, days: model.days)?.reduce(0, +) } 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))) + " ★" } } // MARK: Dashboards struct PadDashboard: View { @Environment(PhoneModel.self) private var model let dashboardID: String @State private var width: CGFloat = 900 var body: some View { if let dash = model.dashboards.first(where: { $0.id == dashboardID }) { VStack(alignment: .leading, spacing: 16) { ScreenHeading(dash.name, subtitle: "Change widgets from your agent on the Mac.") if dash.widgets.isEmpty { TideCard { EmptyState("This dashboard is empty", message: "Ask your agent on the Mac to add widgets, for example “add a chart of my top site's visitors to my dashboard”.") } } DashboardBoard(data: model.portfolio, dashboard: dash, compact: width < 700) } .modifier(WidthReader(width: $width)) } } } enum PadDay { nonisolated(unsafe) static let formatter: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }() static func date(_ s: String) -> Date? { formatter.date(from: s) } }