Branchwell

Graphley / app / commits / d69ca9c4

App source: current code new

written by Branchwell · d69ca9c4c8ff088be085e80dbb7478e9463bddf8

147 files changed

.gitignore added

1+ .build/
2+ DerivedData/
3+ *.xcodeproj/xcuserdata/
4+ *.xcodeproj/
5+ .DS_Store

Apps/Mac/AgentsView.swift added

1+ import SwiftUI
2+ import AnalyticsKit
3+ import AnalyticsUI
4+
5+ struct AgentsView: View {
6+ @Environment(AppModel.self) private var model
7+ @State private var showAll = false
8+
9+ var executable: String { Bundle.main.executablePath ?? "/Applications/Graphley.app/Contents/MacOS/Graphley" }
10+
11+ var body: some View {
12+ VStack(alignment: .leading, spacing: 16) {
13+ ScreenHeading("Agents", subtitle: "Claude Code, Codex or any MCP client can set up Graphley and read your numbers. It all runs on this Mac.")
14+ ViewThatFits(in: .horizontal) {
15+ HStack(alignment: .top, spacing: 16) {
16+ activity.frame(minWidth: 420).layoutPriority(1.4)
17+ side.frame(width: 380)
18+ }
19+ VStack(alignment: .leading, spacing: 16) { side; activity }
20+ }
21+ }
22+ }
23+
24+ var activity: some View {
25+ TideCard("Recent agent activity", subtitle: "Every change an agent makes is listed here.") {
26+ let log = model.workspace.agentLog
27+ if log.isEmpty {
28+ Text("No agent changes yet. When an agent adds a site or builds a dashboard, it shows up here.")
29+ .font(Tide.secondary).foregroundStyle(Tide.muted)
30+ }
31+ VStack(alignment: .leading, spacing: 0) {
32+ ForEach(Array(log.prefix(showAll ? 200 : 20).enumerated()), id: \.element.id) { i, a in
33+ if i > 0 { RowDivider() }
34+ HStack(alignment: .firstTextBaseline, spacing: 10) {
35+ Text(Self.when(a.at)).font(Tide.figure(11.5)).foregroundStyle(Tide.muted).frame(width: 72, alignment: .leading)
36+ (Text(a.client).font(Tide.sans(13.5, .semibold)) + Text(" " + a.summary.prefix(1).lowercased() + a.summary.dropFirst()).font(Tide.sans(13.5)))
37+ .foregroundStyle(Tide.ink)
38+ .frame(maxWidth: .infinity, alignment: .leading)
39+ Text(a.tool).font(Tide.figure(11.5)).foregroundStyle(Tide.muted)
40+ .padding(.vertical, 1).padding(.horizontal, 5).background(Tide.sunk, in: RoundedRectangle(cornerRadius: 4))
41+ }
42+ .padding(.vertical, 8)
43+ }
44+ }
45+ if log.count > 20 && !showAll {
46+ Button("Show All") { showAll = true }.buttonStyle(.tide(.quiet, size: .small))
47+ }
48+ }
49+ }
50+
51+ var side: some View {
52+ VStack(alignment: .leading, spacing: 16) {
53+ TideCard("Connect an agent") {
54+ Text("Claude Code").font(Tide.fieldLabel).foregroundStyle(Tide.ink)
55+ CopyBlock("claude mcp add graphley -- \"\(executable)\" --mcp")
56+ Text("Other MCP clients").font(Tide.fieldLabel).foregroundStyle(Tide.ink).padding(.top, 4)
57+ CopyBlock("{\"mcpServers\": {\"graphley\": {\"command\": \"\(executable)\", \"args\": [\"--mcp\"]}}}", wraps: true)
58+ Text("Paste the command in Terminal. Your agent starts Graphley's MCP server whenever it needs it.")
59+ .font(Tide.caption).foregroundStyle(Tide.muted)
60+ }
61+ TideCard("What agents can do") {
62+ VStack(spacing: 0) {
63+ ToggleRow("Let agents make changes", detail: "Add sites and apps, build dashboards and refresh.", isOn: setting(\.agentsCanWrite))
64+ .padding(.bottom, 12)
65+ RowDivider()
66+ ToggleRow("Let agents set keys", detail: "Save an App Store Connect key for you. Turn it off again afterwards.", isOn: setting(\.agentsCanSetKeys))
67+ .padding(.top, 12)
68+ }
69+ }
70+ TideCard("Try asking") {
71+ VStack(alignment: .leading, spacing: 8) {
72+ PromptChip("Set up Graphley with all my Google Analytics sites.")
73+ PromptChip("Add my App Store apps to Graphley and refresh.")
74+ PromptChip("Make a dashboard comparing my top two sites this month.")
75+ }
76+ }
77+ }
78+ }
79+
80+ func setting(_ key: WritableKeyPath<AnalyticsKit.Settings, Bool>) -> Binding<Bool> {
81+ Binding(get: { model.workspace.settings[keyPath: key] }, set: { v in model.updateSettings { $0[keyPath: key] = v } })
82+ }
83+
84+ static func when(_ date: Date) -> String {
85+ let cal = Calendar.current
86+ if cal.isDateInToday(date) { return date.formatted(date: .omitted, time: .shortened) }
87+ if cal.isDateInYesterday(date) { return "Yesterday" }
88+ return date.formatted(.dateTime.month(.abbreviated).day())
89+ }
90+ }

Apps/Mac/Assets.xcassets/AccentColor.colorset/Contents.json added

1+ { "colors" : [
2+ { "color" : { "color-space" : "srgb", "components" : { "red" : "0x1D", "green" : "0x6E", "blue" : "0x8A", "alpha" : "1.000" } }, "idiom" : "universal" },
3+ { "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ], "color" : { "color-space" : "srgb", "components" : { "red" : "0x5D", "green" : "0xB6", "blue" : "0xD2", "alpha" : "1.000" } }, "idiom" : "universal" }
4+ ], "info" : { "author" : "xcode", "version" : 1 } }

Apps/Mac/Assets.xcassets/AppIcon.appiconset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "filename": "icon-16.png",
5+ "idiom": "mac",
6+ "scale": "1x",
7+ "size": "16x16"
8+ },
9+ {
10+ "filename": "icon-32.png",
11+ "idiom": "mac",
12+ "scale": "2x",
13+ "size": "16x16"
14+ },
15+ {
16+ "filename": "icon-32.png",
17+ "idiom": "mac",
18+ "scale": "1x",
19+ "size": "32x32"
20+ },
21+ {
22+ "filename": "icon-64.png",
23+ "idiom": "mac",
24+ "scale": "2x",
25+ "size": "32x32"
26+ },
27+ {
28+ "filename": "icon-128.png",
29+ "idiom": "mac",
30+ "scale": "1x",
31+ "size": "128x128"
32+ },
33+ {
34+ "filename": "icon-256.png",
35+ "idiom": "mac",
36+ "scale": "2x",
37+ "size": "128x128"
38+ },
39+ {
40+ "filename": "icon-256.png",
41+ "idiom": "mac",
42+ "scale": "1x",
43+ "size": "256x256"
44+ },
45+ {
46+ "filename": "icon-512.png",
47+ "idiom": "mac",
48+ "scale": "2x",
49+ "size": "256x256"
50+ },
51+ {
52+ "filename": "icon-512.png",
53+ "idiom": "mac",
54+ "scale": "1x",
55+ "size": "512x512"
56+ },
57+ {
58+ "filename": "icon-1024.png",
59+ "idiom": "mac",
60+ "scale": "2x",
61+ "size": "512x512"
62+ }
63+ ],
64+ "info": {
65+ "author": "xcode",
66+ "version": 1
67+ }
68+ }

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-1024.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-128.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-16.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-256.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-32.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-512.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-64.png added

Not a text file.

Apps/Mac/Assets.xcassets/Contents.json added

1+ { "info" : { "author" : "xcode", "version" : 1 } }

Apps/Mac/ContentView.swift added

1+ import SwiftUI
2+ import UniformTypeIdentifiers
3+ import AnalyticsKit
4+ import AnalyticsUI
5+
6+ enum SidebarItem: Hashable { case overview, apps, dashboard(String), agents, sources, settings, site(String) }
7+
8+ /// The main window: our own sidebar rows inside the native sidebar, and one screen on the right.
9+ /// Layout and copy follow design/DESIGN.md.
10+ struct ContentView: View {
11+ @Environment(AppModel.self) private var model
12+
13+ var body: some View {
14+ NavigationSplitView {
15+ Sidebar()
16+ .navigationSplitViewColumnWidth(min: 200, ideal: 220)
17+ } detail: {
18+ ScrollView {
19+ screen
20+ .padding(24)
21+ .frame(maxWidth: narrow ? 728 : .infinity, alignment: .leading)
22+ .frame(maxWidth: .infinity, alignment: .leading)
23+ .background(OverlayScrollers())
24+ }
25+ .background(Tide.surface)
26+ .navigationTitle(title)
27+ .modifier(TopBar(showsRange: showsRange))
28+ }
29+ }
30+
31+ @ViewBuilder var screen: some View {
32+ switch model.selection {
33+ case .overview: OverviewView()
34+ case .apps: AppStoreView()
35+ case .dashboard(let id): DashboardView(dashboardID: id)
36+ case .agents: AgentsView()
37+ case .sources: SourcesView()
38+ case .settings: SettingsView()
39+ case .site(let id): SiteView(siteID: id)
40+ }
41+ }
42+
43+ /// Forms read best at a fixed width; data screens use the whole window.
44+ var narrow: Bool { [.sources, .settings].contains(model.selection) }
45+
46+ /// The range only changes Overview, App Store and site screens (dashboard widgets have their own days).
47+ var showsRange: Bool {
48+ switch model.selection {
49+ case .overview, .apps, .site: true
50+ default: false
51+ }
52+ }
53+
54+ var title: String {
55+ switch model.selection {
56+ case .overview: "Overview"
57+ case .apps: "Apps"
58+ case .dashboard(let id): model.workspace.dashboards.first { $0.id == id }?.name ?? "Dashboard"
59+ case .agents: "Agents"
60+ case .sources: "Sources & keys"
61+ case .settings: "Settings"
62+ case .site(let id): model.sites.first { $0.id == id }?.name ?? "Site"
63+ }
64+ }
65+ }
66+
67+ // MARK: Top bar
68+
69+ /// One calm top bar (design/DESIGN.md 2.3): the range pill and the refresh pill, both 30 pt,
70+ /// 12 pt apart, ending in line with the cards below. Our own controls, with the system glass off.
71+ /// Without the title, toolbar items flow from the leading edge, so a flexible spacer pushes ours right.
72+ struct TopBar: ViewModifier {
73+ let showsRange: Bool
74+ func body(content: Content) -> some View {
75+ if #available(macOS 26, *) {
76+ content.toolbar(removing: .title).toolbar {
77+ ToolbarSpacer(.flexible)
78+ ToolbarItem { TopBarCluster(showsRange: showsRange) }
79+ .sharedBackgroundVisibility(.hidden)
80+ }
81+ } else {
82+ content.toolbar { ToolbarItem { TopBarCluster(showsRange: showsRange) } }
83+ }
84+ }
85+ }
86+
87+ struct TopBarCluster: View {
88+ let showsRange: Bool
89+ @Environment(AppModel.self) private var model
90+ /// Extra space after the refresh pill so it ends 24 pt from the window edge, like the cards.
91+ static let trailingNudge: CGFloat = 20
92+
93+ var body: some View {
94+ @Bindable var model = model
95+ HStack(spacing: 12) {
96+ if showsRange { RangeSelector(selection: $model.range) }
97+ RefreshPill(status: status, refresh: { Task { await model.refresh() } }, openSources: { model.selection = .sources })
98+ }
99+ .padding(.trailing, Self.trailingNudge)
100+ .transaction { $0.animation = nil }
101+ }
102+
103+ var status: RefreshPillStatus {
104+ if model.refreshing { return .refreshing }
105+ if !model.failures.isEmpty { return .failed(model.failures.count) }
106+ guard let at = model.workspace.settings.lastRefreshAt else {
107+ // Numbers can arrive without an in-app refresh (an agent, an older version), so say how fresh they are.
108+ guard let day = model.points.map(\.day).max(), let date = ISO8601DateFormatter.dayOnly.date(from: day) else { return .never }
109+ return .dataThrough(date.formatted(.dateTime.month(.abbreviated).day()))
110+ }
111+ let when = RefreshTime.describe(at)
112+ return Date.now.timeIntervalSince(at) > 26 * 3600 ? .stale(when) : .fresh(when)
113+ }
114+ }
115+
116+ /// Keeps the detail page's scroll bar in overlay style even when a mouse makes macOS show it always,
117+ /// so the content column (and the top bar lined up with it) is the same width on every screen.
118+ struct OverlayScrollers: NSViewRepresentable {
119+ func makeNSView(context: Context) -> Probe { Probe() }
120+ func updateNSView(_ view: Probe, context: Context) { view.apply() }
121+
122+ final class Probe: NSView {
123+ private var observing = false
124+ override func viewDidMoveToWindow() {
125+ super.viewDidMoveToWindow()
126+ apply()
127+ guard !observing else { return }
128+ observing = true
129+ NotificationCenter.default.addObserver(self, selector: #selector(styleChanged),
130+ name: NSScroller.preferredScrollerStyleDidChangeNotification, object: nil)
131+ }
132+ @objc private func styleChanged() { apply() }
133+ func apply() {
134+ // Set it after the system's own update from the same notification.
135+ DispatchQueue.main.async { [weak self] in self?.enclosingScrollView?.scrollerStyle = .overlay }
136+ }
137+ }
138+ }
139+
140+ enum RefreshTime {
141+ static func describe(_ date: Date) -> String {
142+ let cal = Calendar.current
143+ if cal.isDateInToday(date) { return date.formatted(date: .omitted, time: .shortened) }
144+ if cal.isDateInYesterday(date) { return "yesterday" }
145+ let days = cal.dateComponents([.day], from: date, to: .now).day ?? 0
146+ return days < 7 ? "\(days) days ago" : date.formatted(.dateTime.month(.abbreviated).day())
147+ }
148+ }
149+
150+ // MARK: Sidebar
151+
152+ struct Sidebar: View {
153+ @Environment(AppModel.self) private var model
154+ /// The site being dragged to a new place in the list.
155+ @State private var dragging: String?
156+
157+ var body: some View {
158+ VStack(spacing: 0) {
159+ ScrollView {
160+ VStack(alignment: .leading, spacing: 2) {
161+ SectionLabel("Portfolio")
162+ SidebarRow("Overview", icon: "chart.xyaxis.line", item: .overview)
163+ SidebarRow("Apps", icon: "arrow.down.app", item: .apps)
164+ ForEach(model.workspace.dashboards) { d in SidebarRow(d.name, icon: "rectangle.3.group", item: .dashboard(d.id)) }
165+ SidebarRow("Agents", icon: "terminal", item: .agents)
166+ SidebarRow("Sources & keys", icon: "key.horizontal", item: .sources)
167+
168+ SectionLabel("Sites")
169+ if model.sites.isEmpty {
170+ VStack(alignment: .leading, spacing: 6) {
171+ Text("No sites yet").font(Tide.secondary).foregroundStyle(Tide.muted)
172+ Button("Add Sites…") { model.selection = .sources; model.wantsSitePicker = model.googleConnected }
173+ .buttonStyle(.tide(.quiet, size: .small))
174+ }
175+ .padding(.horizontal, 10)
176+ }
177+ ForEach(model.sites) { site in
178+ SidebarRow(site.name, dot: Tide.color(for: site), count: model.total(.users, site: site.id, days: model.range), item: .site(site.id))
179+ .opacity(dragging == site.id ? 0.35 : 1)
180+ .onDrag {
181+ dragging = site.id
182+ return NSItemProvider(object: site.id as NSString)
183+ } preview: {
184+ SiteDragPreview(site: site)
185+ }
186+ .help("Drag to change the order. Your iPhone and iPad use the same order.")
187+ .onDrop(of: [.plainText], delegate: SiteDropDelegate(target: site.id, dragging: $dragging, model: model))
188+ .contextMenu {
189+ Button("Move Up") { withAnimation(.snappy(duration: 0.2)) { model.moveSite(site.id, by: -1) } }
190+ .disabled(model.sites.first?.id == site.id)
191+ Button("Move Down") { withAnimation(.snappy(duration: 0.2)) { model.moveSite(site.id, by: 1) } }
192+ .disabled(model.sites.last?.id == site.id)
193+ }
194+ }
195+ }
196+ .padding(.horizontal, 10).padding(.bottom, 10)
197+ // A drop in the gaps between rows still ends the drag cleanly.
198+ .onDrop(of: [.plainText], isTargeted: nil) { _ in
199+ let wasDragging = dragging != nil
200+ dragging = nil
201+ return wasDragging
202+ }
203+ }
204+ .onChange(of: model.selection) { dragging = nil }
205+ VStack(alignment: .leading, spacing: 6) {
206+ SidebarRow("Settings", icon: "gearshape", item: .settings)
207+ Label(iPhoneStatus, systemImage: "iphone").font(Tide.caption).foregroundStyle(Tide.muted)
208+ .labelStyle(SmallIconLabel()).padding(.horizontal, 10)
209+ }
210+ .padding(.horizontal, 10).padding(.vertical, 10)
211+ }
212+ .focusable()
213+ .focusEffectDisabled()
214+ .onMoveCommand { direction in move(direction) }
215+ }
216+
217+ var iPhoneStatus: String {
218+ let s = model.workspace.settings
219+ guard s.shareWithIPhone else { return "iPhone sharing is off" }
220+ guard let at = s.lastSharedAt else { return "iPhone: not shared yet" }
221+ return "iPhone: updated \(RefreshTime.describe(at))"
222+ }
223+
224+ var order: [SidebarItem] {
225+ [.overview, .apps] + model.workspace.dashboards.map { .dashboard($0.id) } + [.agents, .sources] + model.sites.map { .site($0.id) } + [.settings]
226+ }
227+
228+ func move(_ direction: MoveCommandDirection) {
229+ guard let i = order.firstIndex(of: model.selection) else { return }
230+ switch direction {
231+ case .up where i > 0: model.selection = order[i - 1]
232+ case .down where i < order.count - 1: model.selection = order[i + 1]
233+ default: break
234+ }
235+ }
236+ }
237+
238+ /// Live reordering: as the dragged site passes over another row, it takes that row's place, so the
239+ /// list shows the new order before the drop. The order is saved as it changes.
240+ struct SiteDropDelegate: DropDelegate {
241+ let target: String
242+ @Binding var dragging: String?
243+ let model: AppModel
244+
245+ func validateDrop(info: DropInfo) -> Bool { dragging != nil }
246+
247+ func dropEntered(info: DropInfo) {
248+ guard let dragging, dragging != target else { return }
249+ withAnimation(.snappy(duration: 0.2)) { model.moveSite(dragging, to: target) }
250+ }
251+
252+ func dropUpdated(info: DropInfo) -> DropProposal? { DropProposal(operation: .move) }
253+
254+ func performDrop(info: DropInfo) -> Bool {
255+ dragging = nil
256+ return true
257+ }
258+ }
259+
260+ struct SiteDragPreview: View {
261+ let site: Site
262+ var body: some View {
263+ HStack(spacing: 8) {
264+ Circle().fill(Tide.color(for: site)).frame(width: 8, height: 8)
265+ Text(site.name).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink)
266+ }
267+ .padding(.horizontal, 12).frame(height: 28)
268+ .background(Tide.surface, in: RoundedRectangle(cornerRadius: 8))
269+ .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Tide.line2))
270+ }
271+ }
272+
273+ struct SmallIconLabel: LabelStyle {
274+ func makeBody(configuration: Configuration) -> some View {
275+ HStack(spacing: 6) { configuration.icon.font(.system(size: 11)); configuration.title }
276+ }
277+ }
278+
279+ struct SectionLabel: View {
280+ let text: String
281+ init(_ text: String) { self.text = text }
282+ var body: some View {
283+ Text(text.uppercased()).font(Tide.sectionLabel).tracking(0.8).foregroundStyle(Tide.muted)
284+ .padding(.leading, 10).padding(.top, 14).padding(.bottom, 6)
285+ .accessibilityAddTraits(.isHeader)
286+ }
287+ }
288+
289+ struct SidebarRow: View {
290+ let title: String, icon: String?, dot: Color?, count: Double?, item: SidebarItem
291+ @Environment(AppModel.self) private var model
292+ @Environment(\.colorScheme) private var scheme
293+ @State private var hover = false
294+
295+ init(_ title: String, icon: String? = nil, dot: Color? = nil, count: Double? = nil, item: SidebarItem) {
296+ self.title = title; self.icon = icon; self.dot = dot; self.count = count; self.item = item
297+ }
298+
299+ var body: some View {
300+ let selected = model.selection == item
301+ Button { model.selection = item } label: {
302+ HStack(spacing: 8) {
303+ if let icon {
304+ Image(systemName: icon).font(.system(size: 14, weight: .medium)).frame(width: 18)
305+ .foregroundStyle(selected ? Tide.accentInk : Tide.muted)
306+ } else if let dot {
307+ Circle().fill(dot).frame(width: 8, height: 8).frame(width: 18)
308+ }
309+ Text(title).font(Tide.sans(13, .medium)).lineLimit(1).truncationMode(.tail)
310+ .foregroundStyle(selected ? Tide.accentInk : Tide.ink)
311+ Spacer(minLength: 4)
312+ if let count {
313+ Text(Tide.number(count)).font(Tide.figure(11.5))
314+ .foregroundStyle(selected ? Tide.accentInk.opacity(0.75) : Tide.muted)
315+ }
316+ }
317+ .padding(.horizontal, 10)
318+ .frame(height: 28)
319+ .background(selected ? Tide.fill : hover ? (scheme == .dark ? Tide.surface2 : Tide.sunk) : .clear, in: RoundedRectangle(cornerRadius: 8))
320+ .contentShape(RoundedRectangle(cornerRadius: 8))
321+ }
322+ .buttonStyle(.plain)
323+ .onHover { hover = $0 }
324+ .accessibilityAddTraits(selected ? .isSelected : [])
325+ }
326+ }

Apps/Mac/GoogleSignIn.swift added

1+ import AppKit
2+ import CryptoKit
3+ import Network
4+ import AnalyticsKit
5+
6+ /// Google sign-in for installed apps: loopback redirect + PKCE. Opens the browser, waits for the
7+ /// redirect on 127.0.0.1, swaps the code for a refresh token and saves it in the Keychain.
8+ @MainActor
9+ final class GoogleSignIn {
10+ private var listener: NWListener?
11+
12+ func run() async throws {
13+ let verifier = Self.randomURLSafe(64)
14+ let challenge = Data(SHA256.hash(data: Data(verifier.utf8))).base64URLEncoded
15+ let state = Self.randomURLSafe(24)
16+ let clientID = Keychain.get(.googleClientID) ?? GoogleAuth.defaultClientID
17+
18+ let (port, codeStream) = try await startListener(state: state)
19+ let redirect = "http://127.0.0.1:\(port)"
20+ var c = URLComponents(string: "https://accounts.google.com/o/oauth2/v2/auth")!
21+ c.queryItems = [
22+ .init(name: "client_id", value: clientID), .init(name: "redirect_uri", value: redirect),
23+ .init(name: "response_type", value: "code"), .init(name: "scope", value: GoogleAuth.scope),
24+ .init(name: "code_challenge", value: challenge), .init(name: "code_challenge_method", value: "S256"),
25+ .init(name: "state", value: state), .init(name: "access_type", value: "offline"), .init(name: "prompt", value: "consent")
26+ ]
27+ NSWorkspace.shared.open(c.url!)
28+ defer { listener?.cancel() }
29+
30+ var received: String?
31+ for try await value in codeStream { received = value; break }
32+ guard let code = received else { throw AnalyticsError.notSignedIn("Google") }
33+ var r = URLRequest(url: URL(string: "https://oauth2.googleapis.com/token")!)
34+ r.httpMethod = "POST"
35+ r.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
36+ var body = URLComponents()
37+ body.queryItems = [.init(name: "client_id", value: clientID), .init(name: "code", value: code), .init(name: "code_verifier", value: verifier),
38+ .init(name: "grant_type", value: "authorization_code"), .init(name: "redirect_uri", value: redirect)]
39+ r.httpBody = Data((body.percentEncodedQuery ?? "").utf8)
40+ let (data, _) = try await URLSession.shared.data(for: r)
41+ let json = (try JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
42+ guard let refresh = json["refresh_token"] as? String else { throw AnalyticsError.badResponse("Google sign-in") }
43+ try Keychain.set(refresh, for: .googleRefreshToken)
44+ }
45+
46+ /// Listens on a free loopback port and yields the `code` from the first valid redirect.
47+ private func startListener(state: String) async throws -> (UInt16, AsyncThrowingStream<String, Error>) {
48+ let params = NWParameters.tcp
49+ params.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any)
50+ let listener = try NWListener(using: params)
51+ self.listener = listener
52+ let stream = AsyncThrowingStream<String, Error> { continuation in
53+ listener.newConnectionHandler = { conn in
54+ conn.start(queue: .main)
55+ conn.receive(minimumIncompleteLength: 1, maximumLength: 16_384) { data, _, _, _ in
56+ let request = String(decoding: data ?? Data(), as: UTF8.self)
57+ let path = request.split(separator: " ").dropFirst().first.map(String.init) ?? "/"
58+ let items = URLComponents(string: "http://x" + path)?.queryItems ?? []
59+ let code = items.first { $0.name == "code" }?.value
60+ let ok = code != nil && items.first { $0.name == "state" }?.value == state
61+ let page = ok ? "Signed in. You can close this tab and return to the app." : "Sign-in did not finish. Return to the app and try again."
62+ let response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n\(page)"
63+ conn.send(content: Data(response.utf8), completion: .contentProcessed { _ in conn.cancel() })
64+ if ok, let code { continuation.yield(code); continuation.finish() }
65+ }
66+ }
67+ }
68+ let port: UInt16 = try await withCheckedThrowingContinuation { cont in
69+ listener.stateUpdateHandler = { s in
70+ switch s {
71+ case .ready: cont.resume(returning: listener.port?.rawValue ?? 0); listener.stateUpdateHandler = nil
72+ case .failed(let e): cont.resume(throwing: e); listener.stateUpdateHandler = nil
73+ default: break
74+ }
75+ }
76+ listener.start(queue: .main)
77+ }
78+ return (port, stream)
79+ }
80+
81+ static func randomURLSafe(_ count: Int) -> String {
82+ var bytes = [UInt8](repeating: 0, count: count)
83+ _ = SecRandomCopyBytes(kSecRandomDefault, count, &bytes)
84+ return Data(bytes).base64URLEncoded
85+ }
86+ }
87+
88+ extension Data {
89+ var base64URLEncoded: String {
90+ base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
91+ }
92+ }

Apps/Mac/GraphleyMac.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>com.apple.developer.icloud-container-identifiers</key>
6+ <array>
7+ <string>iCloud.com.protomota.graphley</string>
8+ </array>
9+ <key>com.apple.developer.icloud-services</key>
10+ <array>
11+ <string>CloudKit</string>
12+ </array>
13+ <key>com.apple.security.app-sandbox</key>
14+ <true/>
15+ <key>com.apple.security.files.user-selected.read-only</key>
16+ <true/>
17+ <key>com.apple.security.network.client</key>
18+ <true/>
19+ <key>com.apple.security.network.server</key>
20+ <true/>
21+ <key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
22+ <array>
23+ <string>com.protomota.graphley-spks</string>
24+ <string>com.protomota.graphley-spki</string>
25+ </array>
26+ </dict>
27+ </plist>

Apps/Mac/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Graphley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleVersion</key>
22+ <string>$(CURRENT_PROJECT_VERSION)</string>
23+ <key>ITSAppUsesNonExemptEncryption</key>
24+ <false/>
25+ <key>LSApplicationCategoryType</key>
26+ <string>public.app-category.business</string>
27+ <key>NSHumanReadableCopyright</key>
28+ <string>A Project ATOM project</string>
29+ <key>SUEnableInstallerLauncherService</key>
30+ <true/>
31+ <key>SUFeedURL</key>
32+ <string>$(GRAPHLEY_UPDATE_FEED)</string>
33+ <key>SUPublicEDKey</key>
34+ <string>$(GRAPHLEY_UPDATE_PUBLIC_KEY)</string>
35+ </dict>
36+ </plist>

Apps/Mac/MacApp.swift added

1+ import SwiftUI
2+ import AppKit
3+ import OSLog
4+ import AnalyticsKit
5+ import AnalyticsUI
6+
7+ /// `Graphley --mcp` runs the STDIO MCP server on the same local store (Inkspring pattern).
8+ /// Without it, the normal Mac app starts.
9+ @main
10+ enum Entry {
11+ static func main() {
12+ if CommandLine.arguments.contains("--mcp") {
13+ let semaphore = DispatchSemaphore(value: 0)
14+ Task.detached {
15+ do { await MCPServer(store: try WorkspaceStore()).run() }
16+ catch { FileHandle.standardError.write(Data("Could not open the workspace: \(error)\n".utf8)) }
17+ semaphore.signal()
18+ }
19+ semaphore.wait()
20+ exit(0)
21+ }
22+ Tide.registerFonts()
23+ AnalyticsMacApp.main()
24+ }
25+ }
26+
27+ struct AnalyticsMacApp: App {
28+ @State private var model = AppModel()
29+ @StateObject private var updates = AppUpdates()
30+ var body: some Scene {
31+ WindowGroup("Graphley") {
32+ ContentView().environment(model).environmentObject(updates).frame(minWidth: 900, idealWidth: 1280, minHeight: 600, idealHeight: 820)
33+ .task { await model.start() }
34+ }
35+ .defaultSize(width: 1280, height: 820)
36+ .commands {
37+ CommandGroup(after: .appInfo) {
38+ if updates.isAvailable { CheckForUpdatesButton(updates: updates) }
39+ }
40+ // Settings is a screen in the main window, not a separate window.
41+ CommandGroup(replacing: .appSettings) {
42+ Button("Settings…") { model.selection = .settings }.keyboardShortcut(",")
43+ }
44+ CommandGroup(after: .newItem) {
45+ Button("Refresh Now") { Task { await model.refresh() } }.keyboardShortcut("r")
46+ }
47+ CommandGroup(after: .sidebar) {
48+ Button("Last 7 Days") { model.range = 7 }.keyboardShortcut("1")
49+ Button("Last 30 Days") { model.range = 30 }.keyboardShortcut("2")
50+ Button("Last 90 Days") { model.range = 90 }.keyboardShortcut("3")
51+ }
52+ }
53+ }
54+ }
55+
56+ @MainActor @Observable
57+ final class AppModel {
58+ let store: WorkspaceStore
59+ let cloud = SnapshotSync()
60+ var workspace = Workspace()
61+ var points: [DataPoint] = []
62+ var lastReport: Refresher.Report?
63+ var refreshing = false
64+ /// The house iCloud Sync and Diagnostics status for Settings → iPhone and iPad (same fields as Inkspring's).
65+ var cloudStatus = CloudSyncStatus()
66+ var checkingCloud = false
67+ var range = 30
68+ var selection: SidebarItem = .overview
69+ /// Bumped after the app changes the Keychain, so views that read key state redraw.
70+ var keysVersion = 0
71+ /// Set to open the Choose Sites sheet on Sources & keys.
72+ var wantsSitePicker = false
73+ private var started = false
74+ private var loadedVersion: Date?
75+
76+ init() { store = try! WorkspaceStore() }
77+
78+ /// Runs once per app launch. Every new window calls it, so a reopened window must not start
79+ /// another set of loops.
80+ func start() async {
81+ guard !started else { return }
82+ started = true
83+ reload()
84+ #if DEBUG
85+ // `GRAPHLEY_APPEARANCE=light|dark` pins the appearance for screenshots.
86+ switch ProcessInfo.processInfo.environment["GRAPHLEY_APPEARANCE"] {
87+ case "light": NSApp.appearance = NSAppearance(named: .aqua)
88+ case "dark": NSApp.appearance = NSAppearance(named: .darkAqua)
89+ default: break
90+ }
91+ if let path = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT"] {
92+ Task { try? await Task.sleep(for: .seconds(3)); WindowSnapshot.write(to: URL(fileURLWithPath: path)) }
93+ }
94+ // `GRAPHLEY_SNAPSHOT_DIR=/path/` writes one PNG per main screen (overview.png, sources.png, …).
95+ if let dir = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_DIR"] {
96+ Task {
97+ // `GRAPHLEY_SNAPSHOT_SIZE=1280x820` sizes the window first (a locked display opens it at the minimum).
98+ let size = (ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SIZE"] ?? "1280x820").split(separator: "x").compactMap { Double($0) }
99+ if size.count == 2, let window = NSApp.windows.first(where: { $0.isVisible }) { window.setContentSize(NSSize(width: size[0], height: size[1])) }
100+ var screens: [(String, SidebarItem)] = [("overview", .overview), ("app-store", .apps), ("agents", .agents), ("sources", .sources), ("settings", .settings)]
101+ for d in workspace.dashboards {
102+ let slug = d.name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined()
103+ screens.append(("dashboard-\(slug)", .dashboard(d.id)))
104+ }
105+ if let s = sites.first { screens.append(("site", .site(s.id))) }
106+ for (name, item) in screens {
107+ selection = item
108+ try? await Task.sleep(for: .seconds(2))
109+ WindowSnapshot.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name).png"))
110+ // Hold the screen so an outside `screencapture -l` can grab the real window (sidebar included).
111+ try? await Task.sleep(for: .seconds(1.5))
112+ }
113+ }
114+ }
115+ // `GRAPHLEY_TOUR=1` walks every screen on its own (about 3.5 s each) for screen recordings,
116+ // and skips the launch refresh so the recording shows the numbers already in the store.
117+ if ProcessInfo.processInfo.environment["GRAPHLEY_TOUR"] != nil {
118+ Task {
119+ try? await Task.sleep(for: .seconds(3))
120+ var screens: [SidebarItem] = [.overview, .apps] + workspace.dashboards.map { .dashboard($0.id) }
121+ screens += sites.prefix(3).map { .site($0.id) } + [.agents, .sources, .settings, .overview]
122+ for item in screens { selection = item; try? await Task.sleep(for: .seconds(3.5)) }
123+ for r in [90, 7, 30] { range = r; try? await Task.sleep(for: .seconds(2)) }
124+ }
125+ return
126+ }
127+ #endif
128+ // Agents change the store from the --mcp process; pick up their edits.
129+ Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(3)); reload() } }
130+ // Share on every launch, not only when nothing was ever shared: lastSharedAt lives in the store,
131+ // so a Debug build (Development iCloud) or an agent's --mcp refresh can set it without the
132+ // Production database the iPhone reads ever getting the numbers. One small record, so it's cheap.
133+ if workspace.settings.shareWithIPhone && !points.isEmpty { shareSoon() }
134+ // Daily refresh at the configured hour, plus one on launch if today's has not run. Numbers that
135+ // arrived after the last share (an agent's refresh, a failed push) go to the iPhone on the same tick.
136+ Task {
137+ while !Task.isCancelled {
138+ if needsDailyRefresh { await refresh() } else if needsShare { shareSoon() }
139+ try? await Task.sleep(for: .seconds(600))
140+ }
141+ }
142+ }
143+
144+ /// Re-reads the store whenever its files changed on disk. Read errors keep the current values
145+ /// and retry on the next tick instead of being mistaken for "nothing changed".
146+ func reload() {
147+ let version = store.lastModified()
148+ guard version == nil || version != loadedVersion else { return }
149+ do {
150+ let ws = try store.load(), pts = try store.points()
151+ if ws != workspace { workspace = ws }
152+ if pts != points { points = pts }
153+ loadedVersion = version
154+ } catch {
155+ Self.log.error("Could not read the store: \(error.localizedDescription, privacy: .public)")
156+ }
157+ }
158+ static let log = Logger(subsystem: "com.protomota.graphley", category: "store")
159+
160+ var needsDailyRefresh: Bool {
161+ let latest = points.map(\.day).max() ?? ""
162+ let hour = Calendar.current.component(.hour, from: .now)
163+ return latest < (DayKey.lastDays(1).last ?? "") && hour >= workspace.settings.refreshHour
164+ }
165+
166+ /// True when the store has numbers newer than the last copy sent to the iPhone.
167+ var needsShare: Bool {
168+ let s = workspace.settings
169+ guard s.shareWithIPhone, !points.isEmpty, let refreshed = s.lastRefreshAt else { return false }
170+ return (s.lastSharedAt ?? .distantPast) < refreshed
171+ }
172+
173+ func refresh() async {
174+ guard !refreshing else { return }
175+ refreshing = true; defer { refreshing = false }
176+ lastReport = await Refresher(store: store, cloud: cloud).refreshAll()
177+ reload()
178+ await checkCloud(share: false)
179+ }
180+
181+ /// Check Now: asks iCloud for the account, shares the latest numbers when sharing is on (so a
182+ /// rejected record shows its real CloudKit error), then reads back whether iCloud has the snapshot.
183+ func checkCloud(share: Bool = true) async {
184+ guard !checkingCloud, cloud.isAvailable else { return }
185+ checkingCloud = true; defer { checkingCloud = false }
186+ var status = cloudStatus
187+ status.lastCheck = .now
188+ status.clearError()
189+ var checkedAccount = false
190+ do {
191+ status.accountStatus = try await cloud.accountStatusText()
192+ checkedAccount = true
193+ guard status.accountStatus == "Connected" else {
194+ status.error = "This Mac isn't signed in to iCloud. Sign in in System Settings, then check again."
195+ cloudStatus = status
196+ return
197+ }
198+ if share, workspace.settings.shareWithIPhone, let snap = try? store.snapshot(refreshedAt: workspace.settings.lastRefreshAt) {
199+ try await cloud.push(snap)
200+ _ = try? store.update { $0.settings.lastSharedAt = .now }
201+ reload()
202+ }
203+ let date = try await cloud.remoteSnapshotDate()
204+ status.lastCloudContact = .now
205+ status.snapshotFound = date != nil
206+ status.snapshotDate = date
207+ if date == nil, workspace.settings.shareWithIPhone, workspace.settings.lastSharedAt != nil {
208+ status.error = "iCloud accepted the last share but has no snapshot. The CloudKit schema may not be deployed to Production."
209+ }
210+ } catch {
211+ if !checkedAccount { status.accountStatus = "Unavailable" }
212+ status.record(error)
213+ Self.log.error("iCloud check failed: \(String(describing: error), privacy: .public)")
214+ }
215+ cloudStatus = status
216+ }
217+
218+ func keysChanged() { keysVersion += 1 }
219+
220+ /// Reorders the sidebar's sites. Saved right away and, after a short pause so a drag across
221+ /// several rows sends one update, shared with the iPhone so it shows the same order.
222+ func moveSite(_ id: String, to target: String) {
223+ guard workspace.sites.contains(where: { $0.id == id }), id != target else { return }
224+ _ = try? store.update { $0.moveSite(id, to: target) }
225+ reload()
226+ shareSoon()
227+ }
228+
229+ func moveSite(_ id: String, by step: Int) {
230+ _ = try? store.update { $0.moveSite(id, by: step) }
231+ reload()
232+ shareSoon()
233+ }
234+
235+ private var sharePush: Task<Void, Never>?
236+ /// Pushes the store to the iPhone after a short pause (a drag across several rows sends one update).
237+ private func shareSoon() {
238+ sharePush?.cancel()
239+ sharePush = Task { [store, cloud] in
240+ try? await Task.sleep(for: .seconds(1.5))
241+ guard !Task.isCancelled, cloud.isAvailable, let ws = try? store.load(), ws.settings.shareWithIPhone,
242+ let snap = try? store.snapshot(refreshedAt: ws.settings.lastRefreshAt) else { return }
243+ do {
244+ try await cloud.push(snap)
245+ _ = try? store.update { $0.settings.lastSharedAt = .now }
246+ reload()
247+ await checkCloud(share: false)
248+ } catch {
249+ cloudStatus.record(error)
250+ Self.log.error("Could not share with the iPhone: \(String(describing: error), privacy: .public)")
251+ }
252+ }
253+ }
254+
255+ func updateSettings(_ change: (inout AnalyticsKit.Settings) -> Void) {
256+ _ = try? store.update { change(&$0.settings) }
257+ reload()
258+ }
259+
260+ /// Sources whose last refresh failed, keyed by source name.
261+ var failures: [String: String] { lastReport?.failed ?? [:] }
262+ var hasAppStoreKey: Bool {
263+ _ = keysVersion
264+ #if DEBUG
265+ // Unsigned review builds can't read the Keychain; `GRAPHLEY_ASSUME_KEYS=1` shows the App Store cards anyway.
266+ if ProcessInfo.processInfo.environment["GRAPHLEY_ASSUME_KEYS"] != nil { return true }
267+ #endif
268+ return AppStoreConnect().isConfigured
269+ }
270+ var googleConnected: Bool { _ = keysVersion; return GoogleAuth.isConfigured }
271+
272+ var days: [String] { DayKey.lastDays(range) }
273+ var sites: [Site] { workspace.sites.filter { !$0.archived } }
274+ @ObservationIgnored private var portfolioCache: (key: String, data: PortfolioData)?
275+ /// The store indexed for dashboards, rebuilt only when the store changes.
276+ var portfolio: PortfolioData {
277+ let key = "\(loadedVersion?.timeIntervalSince1970 ?? 0)|\(points.count)|\(workspace.sites.count)"
278+ if let c = portfolioCache, c.key == key { return c.data }
279+ let w = workspace
280+ let data = PortfolioData(sites: w.sites, apps: w.apps, socials: w.socials, points: points, reviews: w.reviews, campaigns: w.campaigns, videos: w.videos, caveats: w.caveats)
281+ portfolioCache = (key, data)
282+ return data
283+ }
284+ func series(_ metric: Metric, sites ids: Set<String> = [], days: [String]) -> [Double] { points.daily(metric, subjects: ids, days: days) }
285+ func total(_ metric: Metric, site: String? = nil, days n: Int, offset: Int = 0) -> Double {
286+ let all = DayKey.lastDays(n + offset); return points.daily(metric, subjects: site.map { [$0] } ?? [], days: Array(all.prefix(n))).reduce(0, +)
287+ }
288+ }
289+
290+ #if DEBUG
291+ /// Debug builds only: `GRAPHLEY_SNAPSHOT=/path/out.png` renders the app's own main window (title bar
292+ /// included) to a PNG a few seconds after launch, plus a view-tree `.txt` beside it. Lets agents capture the running app headlessly
293+ /// when the session has no Screen Recording permission.
294+ @MainActor
295+ enum WindowSnapshot {
296+ static func write(to url: URL) {
297+ guard let window = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil }),
298+ let frameView = window.contentView?.superview else { return }
299+ // Always 2x, even on a 1x display. cacheDisplay draws through AppKit, so the sidebar's
300+ // vibrancy list appears; the layer render below is the fallback.
301+ // `GRAPHLEY_SNAPSHOT_SCROLL=end` scrolls each screen to its bottom first (Settings → About on a short display).
302+ if ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SCROLL"] == "end" { scrollToEnd(frameView) }
303+ let size = frameView.bounds.size
304+ if let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * 2), pixelsHigh: Int(size.height * 2), bitsPerSample: 8,
305+ samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) {
306+ rep.size = size
307+ frameView.cacheDisplay(in: frameView.bounds, to: rep)
308+ try? rep.representation(using: .png, properties: [:])?.write(to: url)
309+ }
310+ try? viewTree(frameView).write(to: url.deletingPathExtension().appendingPathExtension("txt"), atomically: true, encoding: .utf8)
311+ }
312+
313+ static func scrollToEnd(_ view: NSView) {
314+ if let scroll = view as? NSScrollView, scroll.frame.width > 500, let document = scroll.documentView {
315+ let y = document.isFlipped ? max(0, document.bounds.height - scroll.contentView.bounds.height) : 0
316+ scroll.contentView.scroll(to: NSPoint(x: 0, y: y)); scroll.reflectScrolledClipView(scroll.contentView)
317+ }
318+ view.subviews.forEach(scrollToEnd)
319+ }
320+
321+ /// Text outline of the window: view classes, frames, table row counts and accessibility labels.
322+ static func viewTree(_ view: NSView, depth: Int = 0) -> String {
323+ var line = String(repeating: " ", count: depth) + "\(type(of: view)) \(view.frame.integral)"
324+ if let table = view as? NSTableView { line += " rows=\(table.numberOfRows)" }
325+ if let label = view.accessibilityLabel(), !label.isEmpty { line += " label=\"\(label)\"" }
326+ return ([line] + view.subviews.map { viewTree($0, depth: depth + 1) }).joined(separator: "\n")
327+ }
328+ }
329+ #endif

Apps/Mac/PrivacyInfo.xcprivacy added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <!-- Graphley collects nothing and tracks nobody. Numbers stay on the user's devices and their own iCloud. -->
4+ <plist version="1.0">
5+ <dict>
6+ <key>NSPrivacyTracking</key>
7+ <false/>
8+ <key>NSPrivacyTrackingDomains</key>
9+ <array/>
10+ <key>NSPrivacyCollectedDataTypes</key>
11+ <array/>
12+ <key>NSPrivacyAccessedAPITypes</key>
13+ <array>
14+ <dict>
15+ <!-- WorkspaceStore.lastModified reads the modification date of the app's own workspace files. -->
16+ <key>NSPrivacyAccessedAPIType</key>
17+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
18+ <key>NSPrivacyAccessedAPITypeReasons</key>
19+ <array>
20+ <string>C617.1</string>
21+ </array>
22+ </dict>
23+ </array>
24+ </dict>
25+ </plist>

Apps/Mac/Screens.swift added

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+ }

Apps/Mac/SettingsView.swift added

1+ import SwiftUI
2+ import AnalyticsKit
3+ import AnalyticsUI
4+
5+ /// Settings, as a screen in the main window (⌘, opens it). Replaces the old separate Settings window.
6+ struct SettingsView: View {
7+ @Environment(AppModel.self) private var model
8+ @EnvironmentObject private var updates: AppUpdates
9+ @Environment(\.openURL) private var openURL
10+ @State private var turnedOnKeys = false
11+
12+ var body: some View {
13+ let s = model.workspace.settings
14+ VStack(alignment: .leading, spacing: 16) {
15+ ScreenHeading("Settings", subtitle: "How Graphley refreshes, shares with your iPhone and iPad, and works with your agents.")
16+
17+ TideCard("Agents") {
18+ VStack(alignment: .leading, spacing: 0) {
19+ ToggleRow("Let agents make changes",
20+ detail: "Agents can add sites and apps, build dashboards and refresh. Every change is listed on the Agents screen.",
21+ isOn: setting(\.agentsCanWrite)).padding(.bottom, 12)
22+ RowDivider()
23+ VStack(alignment: .leading, spacing: 6) {
24+ ToggleRow("Let agents set keys",
25+ detail: "Agents can save an App Store Connect key for you. Leave this off unless you're setting one up.",
26+ isOn: keysToggle)
27+ if turnedOnKeys && s.agentsCanSetKeys {
28+ Text("Turn this off again after your agent saves the key.").font(Tide.caption).foregroundStyle(Tide.attentionText)
29+ }
30+ }
31+ .padding(.vertical, 12)
32+ RowDivider()
33+ Button("Connect an Agent…") { model.selection = .agents }
34+ .buttonStyle(.tide(.quiet)).padding(.top, 8).padding(.leading, -14)
35+ }
36+ }
37+
38+ TideCard("iPhone and iPad") {
39+ ToggleRow("Share with iPhone and iPad through iCloud",
40+ detail: "After each refresh, your Mac puts a copy of the numbers in your private iCloud. Your iPhone and iPad read it. Keys are never shared.",
41+ isOn: setting(\.shareWithIPhone))
42+ Text(iPhoneLine(s)).font(Tide.caption).foregroundStyle(model.failures["iCloud sync"] != nil ? Tide.downText : Tide.muted)
43+ }
44+
45+ TideCard("iCloud Sync", subtitle: "What iCloud has from this Mac. Your iPhone and iPad read the same copy.", icon: "icloud") {
46+ CloudSyncSection(status: model.cloudStatus, busy: model.checkingCloud,
47+ missingMessage: "iCloud has no snapshot from this Mac yet. Turn on sharing above, then check again.") {
48+ Task { await model.checkCloud() }
49+ }
50+ }
51+ .task { if model.cloudStatus.lastCheck == nil { await model.checkCloud(share: false) } }
52+
53+ TideCard("Diagnostics", icon: "stethoscope") {
54+ CloudDiagnosticsSection(status: model.cloudStatus)
55+ }
56+
57+ TideCard("Daily refresh") {
58+ HStack(spacing: 10) {
59+ Text("Refresh every day at").font(Tide.rowTitle).foregroundStyle(Tide.ink)
60+ Menu {
61+ ForEach(0..<24, id: \.self) { h in
62+ Button(Self.hourLabel(h)) { model.updateSettings { $0.refreshHour = h } }
63+ }
64+ } label: {
65+ HStack(spacing: 6) {
66+ Text(Self.hourLabel(s.refreshHour))
67+ Image(systemName: "chevron.up.chevron.down").font(.system(size: 10, weight: .semibold))
68+ }
69+ }
70+ .menuStyle(.button)
71+ .menuIndicator(.hidden)
72+ .buttonStyle(.tide(.secondary))
73+ .fixedSize()
74+ }
75+ Text("Graphley refreshes at this time while it's open. If it was closed, it refreshes when you open it.")
76+ .font(Tide.secondary).foregroundStyle(Tide.muted)
77+ HStack(spacing: 10) {
78+ Button { Task { await model.refresh() } } label: {
79+ if model.refreshing { Label("Refreshing…", systemImage: "arrow.clockwise") } else { Text("Refresh Now") }
80+ }
81+ .buttonStyle(.tide(.secondary)).disabled(model.refreshing)
82+ Text("⌘R").font(Tide.caption).foregroundStyle(Tide.muted)
83+ }
84+ }
85+
86+ TideCard("Updates") {
87+ HStack(alignment: .firstTextBaseline) {
88+ Text("Graphley \(Self.version)").font(Tide.rowTitle).foregroundStyle(Tide.ink)
89+ Spacer()
90+ if updates.isAvailable {
91+ Button("Check for Updates") { updates.check() }.buttonStyle(.tide(.secondary)).disabled(!updates.canCheck)
92+ }
93+ }
94+ Text(updates.isAvailable ? "Graphley checks for updates on its own and asks before installing." : "Updates are off in this build.")
95+ .font(Tide.secondary).foregroundStyle(Tide.muted)
96+ }
97+
98+ TideCard("About") {
99+ HStack(spacing: 12) {
100+ TideMark(size: 44)
101+ VStack(alignment: .leading, spacing: 2) {
102+ Text("Graphley").font(Tide.cardTitle).foregroundStyle(Tide.ink)
103+ Text("Version \(Self.version)").font(Tide.caption).foregroundStyle(Tide.muted)
104+ }
105+ }
106+ Text("Free and open source, public domain (Unlicense). Graphley has no server: your numbers stay on this Mac and in your private iCloud.")
107+ .font(Tide.secondary).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true)
108+ HStack(spacing: 4) {
109+ link("graphley.ai", "https://graphley.ai")
110+ link("Privacy", "https://graphley.ai/privacy/")
111+ }
112+ .padding(.leading, -10)
113+ }
114+ }
115+ }
116+
117+ func link(_ title: String, _ url: String) -> some View {
118+ Button { openURL(URL(string: url)!) } label: {
119+ HStack(spacing: 4) { Text(title); Image(systemName: "arrow.up.right").font(.system(size: 10, weight: .semibold)) }
120+ }
121+ .buttonStyle(.tide(.quiet, size: .small))
122+ }
123+
124+ var keysToggle: Binding<Bool> {
125+ Binding(get: { model.workspace.settings.agentsCanSetKeys },
126+ set: { v in model.updateSettings { $0.agentsCanSetKeys = v }; if v { turnedOnKeys = true } })
127+ }
128+
129+ func setting(_ key: WritableKeyPath<AnalyticsKit.Settings, Bool>) -> Binding<Bool> {
130+ Binding(get: { model.workspace.settings[keyPath: key] }, set: { v in model.updateSettings { $0[keyPath: key] = v } })
131+ }
132+
133+ func iPhoneLine(_ s: AnalyticsKit.Settings) -> String {
134+ if model.failures["iCloud sync"] != nil { return "Couldn't share with your iPhone and iPad. Make sure this Mac is signed in to iCloud." }
135+ guard s.shareWithIPhone else { return "Your iPhone and iPad keep showing the last numbers they received." }
136+ guard let at = s.lastSharedAt else { return "Not shared yet. It happens after the next refresh." }
137+ let day = Calendar.current.isDateInToday(at) ? "today" : Calendar.current.isDateInYesterday(at) ? "yesterday" : at.formatted(.dateTime.month(.abbreviated).day())
138+ return "Last shared \(day) at \(at.formatted(date: .omitted, time: .shortened))."
139+ }
140+
141+ static func hourLabel(_ h: Int) -> String {
142+ let date = Calendar.current.date(bySettingHour: h, minute: 0, second: 0, of: .now) ?? .now
143+ return date.formatted(date: .omitted, time: .shortened)
144+ }
145+
146+ static var version: String {
147+ let info = Bundle.main.infoDictionary ?? [:]
148+ return "\(info["CFBundleShortVersionString"] as? String ?? "?") (\(info["CFBundleVersion"] as? String ?? "?"))"
149+ }
150+ }

Apps/Mac/SourcesView.swift added

1+ import SwiftUI
2+ import CryptoKit
3+ import UniformTypeIdentifiers
4+ import AnalyticsKit
5+ import AnalyticsUI
6+
7+ /// Sources & keys: connect Google Analytics and App Store Connect without an agent (design/DESIGN.md 3.2).
8+ /// Keys go to the Keychain only, never into the workspace or iCloud data.
9+ struct SourcesView: View {
10+ @Environment(AppModel.self) private var model
11+
12+ var body: some View {
13+ VStack(alignment: .leading, spacing: 16) {
14+ ScreenHeading("Sources & keys", subtitle: "Where your numbers come from. Keys stay in your Keychain; your iPhone only gets the numbers.")
15+ GoogleCard()
16+ AppStoreCard()
17+ HStack(spacing: 10) {
18+ Text("App Store ratings").font(Tide.rowTitle).foregroundStyle(Tide.ink)
19+ Text("Public, no key needed").font(Tide.secondary).foregroundStyle(Tide.muted)
20+ Spacer()
21+ StatusPill("On", .ok)
22+ }
23+ .padding(.horizontal, 16)
24+ if !model.failures.isEmpty { ProblemsCard() }
25+ }
26+ }
27+ }
28+
29+ // MARK: Google Analytics
30+
31+ struct GoogleCard: View {
32+ @Environment(AppModel.self) private var model
33+ @State private var signingIn = false
34+ @State private var error: String?
35+ @State private var confirmSignOut = false
36+ @State private var choosingSites = false
37+ @State private var importingServiceAccount = false
38+
39+ var body: some View {
40+ let _ = model.keysVersion
41+ let serviceAccount = GoogleServiceAccountKey.savedEmail
42+ let signedIn = Keychain.has(.googleRefreshToken)
43+ let expired = model.failures.values.contains { $0.contains("invalid_grant") || $0.contains("Sign in to Google") }
44+ TideCard("Google Analytics", icon: "chart.bar.xaxis", padding: 20) {
45+ if signingIn { StatusPill("Checking…", .info) }
46+ else if expired { StatusPill("Sign in again", .error) }
47+ else if serviceAccount != nil || signedIn { StatusPill("Connected", .ok) }
48+ else { StatusPill("Not connected", .neutral) }
49+ } content: {
50+ if let serviceAccount {
51+ para("Connected with the service account \(serviceAccount). \(tracked)")
52+ HStack(spacing: 8) {
53+ Button("Choose Sites…") { choosingSites = true }.buttonStyle(.tide(.secondary))
54+ Button("Remove Key") { confirmSignOut = true }.buttonStyle(.tide(.quietDestructive))
55+ }
56+ } else if signingIn {
57+ para("Finish signing in in your browser, then come back here.")
58+ Button {} label: { Label("Waiting for your browser…", systemImage: "hourglass") }.buttonStyle(.tide(.primary)).disabled(true)
59+ } else if expired {
60+ para("Google ended this sign-in, so your sites stopped updating. Sign in again to pick up where you left off.")
61+ Button("Sign In Again…") { signIn() }.buttonStyle(.tide(.primary))
62+ } else if signedIn {
63+ para("Signed in with read-only access. \(tracked)")
64+ HStack(spacing: 8) {
65+ Button("Choose Sites…") { choosingSites = true }.buttonStyle(.tide(.secondary))
66+ Button("Sign Out") { confirmSignOut = true }.buttonStyle(.tide(.quietDestructive))
67+ }
68+ } else {
69+ para("Sign in with Google to read visitors, sessions and page views for your sites. Graphley only asks for read-only access.")
70+ HStack(spacing: 8) {
71+ Button("Sign In with Google…") { signIn() }.buttonStyle(.tide(.primary))
72+ Button("Use a Service Account Key…") { importingServiceAccount = true }.buttonStyle(.tide(.quiet))
73+ }
74+ }
75+ if let error {
76+ Label(error, systemImage: "exclamationmark.circle.fill").font(Tide.caption).foregroundStyle(Tide.downText)
77+ }
78+ }
79+ .confirmationDialog(serviceAccount != nil ? "Remove the service account key?" : "Sign out of Google?", isPresented: $confirmSignOut) {
80+ Button(serviceAccount != nil ? "Remove Key" : "Sign Out", role: .destructive) {
81+ if serviceAccount != nil { GoogleServiceAccountKey.remove() } else { Keychain.remove(.googleRefreshToken) }
82+ model.keysChanged()
83+ }
84+ Button("Cancel", role: .cancel) {}
85+ } message: {
86+ Text("Graphley will stop updating your sites. The numbers you already have stay.")
87+ }
88+ .sheet(isPresented: $choosingSites) { ChooseSitesSheet() }
89+ .fileImporter(isPresented: $importingServiceAccount, allowedContentTypes: [.json]) { result in
90+ error = nil
91+ do {
92+ let url = try result.get()
93+ let ok = url.startAccessingSecurityScopedResource(); defer { if ok { url.stopAccessingSecurityScopedResource() } }
94+ try GoogleServiceAccountKey.save(json: String(contentsOf: url, encoding: .utf8))
95+ model.keysChanged()
96+ choosingSites = true
97+ } catch {
98+ self.error = "That file isn't a Google service account key. Download a JSON key from Google Cloud › IAM › Service accounts › Keys."
99+ }
100+ }
101+ .onAppear { if model.wantsSitePicker { model.wantsSitePicker = false; choosingSites = true } }
102+ }
103+
104+ var tracked: String {
105+ let n = model.sites.count
106+ return n == 0 ? "No sites tracked yet." : "\(n) \(n == 1 ? "site" : "sites") tracked."
107+ }
108+
109+ func para(_ text: String) -> some View {
110+ Text(text).font(Tide.text).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true)
111+ }
112+
113+ func signIn() {
114+ signingIn = true; error = nil
115+ Task {
116+ do {
117+ try await GoogleSignIn().run()
118+ model.keysChanged()
119+ if model.sites.isEmpty { choosingSites = true }
120+ } catch {
121+ self.error = "Sign-in didn't finish. Try again, and choose Allow when Google asks."
122+ }
123+ signingIn = false
124+ }
125+ }
126+ }
127+
128+ /// Pick which GA4 properties to track. New ones become sites; unchecked ones are archived (history kept).
129+ struct ChooseSitesSheet: View {
130+ @Environment(AppModel.self) private var model
131+ @Environment(\.dismiss) private var dismiss
132+ @State private var properties: [GoogleAnalytics.Property] = []
133+ @State private var chosen: Set<String> = []
134+ @State private var loading = true
135+ @State private var error: String?
136+
137+ var body: some View {
138+ VStack(alignment: .leading, spacing: 14) {
139+ VStack(alignment: .leading, spacing: 4) {
140+ Text("Choose sites to track").font(Tide.sans(17, .semibold)).foregroundStyle(Tide.ink)
141+ Text("These are the Google Analytics properties your account can read.").font(Tide.secondary).foregroundStyle(Tide.muted)
142+ }
143+ Group {
144+ if loading {
145+ HStack { ProgressView().controlSize(.small); Text("Finding your properties…").font(Tide.secondary).foregroundStyle(Tide.muted) }
146+ .frame(maxWidth: .infinity, minHeight: 120)
147+ } else if let error {
148+ Text(error).font(Tide.secondary).foregroundStyle(Tide.downText).frame(maxWidth: .infinity, minHeight: 120, alignment: .leading)
149+ } else if properties.isEmpty {
150+ Text("This Google account can't read any Google Analytics properties yet.").font(Tide.secondary).foregroundStyle(Tide.muted)
151+ .frame(maxWidth: .infinity, minHeight: 120, alignment: .leading)
152+ } else {
153+ ScrollView {
154+ VStack(spacing: 0) {
155+ ForEach(Array(properties.enumerated()), id: \.element.id) { i, p in
156+ if i > 0 { RowDivider() }
157+ PropertyRow(property: p, isOn: Binding(get: { chosen.contains(p.id) },
158+ set: { if $0 { chosen.insert(p.id) } else { chosen.remove(p.id) } }))
159+ }
160+ }
161+ }
162+ .frame(maxHeight: 360)
163+ }
164+ }
165+ HStack {
166+ Spacer()
167+ Button("Cancel") { dismiss() }.buttonStyle(.tide(.quiet)).keyboardShortcut(.cancelAction)
168+ Button(saveTitle) { save() }.buttonStyle(.tide(.primary)).keyboardShortcut(.defaultAction).disabled(loading || error != nil)
169+ }
170+ }
171+ .padding(20)
172+ .frame(width: 520)
173+ .background(Tide.surface)
174+ .task { await load() }
175+ }
176+
177+ var current: Set<String> { Set(model.sites.compactMap(\.ga4PropertyID)) }
178+ var saveTitle: String { chosen == current ? "Save" : "Track \(chosen.count) \(chosen.count == 1 ? "Site" : "Sites")" }
179+
180+ func load() async {
181+ do {
182+ properties = try await GoogleAnalytics().properties().sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
183+ chosen = current
184+ } catch {
185+ self.error = "Couldn't reach Google. Check your internet connection and try again."
186+ }
187+ loading = false
188+ }
189+
190+ func save() {
191+ let byID = Dictionary(properties.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
192+ _ = try? model.store.update { ws in
193+ for i in ws.sites.indices {
194+ guard let pid = ws.sites[i].ga4PropertyID, byID[pid] != nil else { continue }
195+ ws.sites[i].archived = !chosen.contains(pid)
196+ }
197+ for pid in chosen where !ws.sites.contains(where: { $0.ga4PropertyID == pid }) {
198+ guard let p = byID[pid] else { continue }
199+ let used = Set(ws.sites.filter { !$0.archived }.map(\.colorIndex))
200+ let color = (0..<7).first { !used.contains($0) } ?? ws.sites.count % 7
201+ ws.sites.append(Site(id: Self.slug(p.name, taken: Set(ws.sites.map(\.id))), name: p.name, ga4PropertyID: pid, colorIndex: color))
202+ }
203+ }
204+ model.reload()
205+ dismiss()
206+ Task { await model.refresh() }
207+ }
208+
209+ static func slug(_ s: String, taken: Set<String>) -> String {
210+ let base = s.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined().split(separator: "-").joined(separator: "-")
211+ var candidate = base.isEmpty ? "site" : base, n = 2
212+ while taken.contains(candidate) { candidate = "\(base)-\(n)"; n += 1 }
213+ return candidate
214+ }
215+ }
216+
217+ struct PropertyRow: View {
218+ let property: GoogleAnalytics.Property
219+ @Binding var isOn: Bool
220+ var body: some View {
221+ Button { isOn.toggle() } label: {
222+ HStack(spacing: 12) {
223+ ZStack {
224+ RoundedRectangle(cornerRadius: 4).fill(isOn ? Tide.fill : Tide.surface)
225+ RoundedRectangle(cornerRadius: 4).strokeBorder(isOn ? Tide.fill : Tide.control)
226+ if isOn { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(Tide.accentInk) }
227+ }
228+ .frame(width: 16, height: 16)
229+ VStack(alignment: .leading, spacing: 2) {
230+ Text(property.name).font(Tide.rowTitle).foregroundStyle(Tide.ink)
231+ Text("Property \(property.id) · \(property.account)").font(Tide.code).foregroundStyle(Tide.muted)
232+ }
233+ Spacer()
234+ }
235+ .padding(.vertical, 8).contentShape(Rectangle())
236+ }
237+ .buttonStyle(.plain)
238+ .accessibilityAddTraits(isOn ? .isSelected : [])
239+ }
240+ }
241+
242+ // MARK: App Store Connect
243+
244+ struct AppStoreCard: View {
245+ @Environment(AppModel.self) private var model
246+ @Environment(\.openURL) private var openURL
247+ @State private var replacing = false
248+ @State private var keyID = ""
249+ @State private var issuerID = ""
250+ @State private var vendor = ""
251+ @State private var key: KeyFile?
252+ @State private var keyIDHelp = "10 letters and numbers."
253+ @State private var showErrors = false
254+ @State private var saving = false
255+ @State private var failure: String?
256+ @State private var justSaved = false
257+ @State private var confirmRemove = false
258+ @State private var agentOpen = false
259+
260+ struct KeyFile: Equatable { var name: String; var path: String; var pem: String }
261+
262+ var body: some View {
263+ let _ = model.keysVersion
264+ let saved = AppStoreConnect.Credentials.saved
265+ let showForm = saved == nil || replacing
266+ TideCard("App Store Connect", icon: "arrow.down.app", padding: 20) {
267+ if saving { StatusPill("Checking…", .info) }
268+ else if failure != nil { StatusPill("Key not accepted", .error) }
269+ else if saved != nil { StatusPill("Key saved", .ok) }
270+ else { StatusPill("Not set up", .neutral) }
271+ } content: {
272+ if showForm { form(replacing: saved != nil) } else if let saved { savedView(saved) }
273+ }
274+ .confirmationDialog("Remove the App Store Connect key?", isPresented: $confirmRemove) {
275+ Button("Remove Key", role: .destructive) { AppStoreConnect.Credentials.remove(); justSaved = false; model.keysChanged() }
276+ Button("Cancel", role: .cancel) {}
277+ } message: {
278+ Text("Graphley will stop updating App Store downloads. The numbers you already have stay.")
279+ }
280+ }
281+
282+ // Saved state: the IDs (not secret) and what to do next. The private key is never shown.
283+ @ViewBuilder func savedView(_ c: AppStoreConnect.Credentials) -> some View {
284+ Text("Key ID \(c.keyID) · Issuer \(c.issuerID.prefix(8))…\(c.issuerID.suffix(4)) · Vendor \(c.vendorNumber)")
285+ .font(Tide.code).foregroundStyle(Tide.ink2).textSelection(.enabled)
286+ if justSaved {
287+ HStack(spacing: 10) {
288+ Text("The key works. Downloads show up after the next refresh.").font(Tide.caption).foregroundStyle(Tide.up)
289+ Button("Refresh Now") { Task { await model.refresh() } }.buttonStyle(.tide(.secondary, size: .small)).disabled(model.refreshing)
290+ }
291+ } else if model.workspace.apps.isEmpty {
292+ HStack(spacing: 10) {
293+ Text("No apps added yet. Ask your agent to add them:").font(Tide.caption).foregroundStyle(Tide.muted)
294+ PromptChip("Add my App Store apps to Graphley and refresh.")
295+ }
296+ } else if let at = model.workspace.settings.lastRefreshAt, model.failures["App Store downloads"] == nil {
297+ Text("Updated downloads for \(model.workspace.apps.count) \(model.workspace.apps.count == 1 ? "app" : "apps") \(RefreshTime.describe(at)).")
298+ .font(Tide.caption).foregroundStyle(Tide.muted)
299+ }
300+ HStack(spacing: 8) {
301+ Button("Replace Key…") {
302+ keyID = c.keyID; issuerID = c.issuerID; vendor = c.vendorNumber; key = nil
303+ failure = nil; showErrors = false; replacing = true
304+ }
305+ .buttonStyle(.tide(.secondary))
306+ Button("Remove Key") { confirmRemove = true }.buttonStyle(.tide(.quietDestructive))
307+ }
308+ }
309+
310+ @ViewBuilder func form(replacing: Bool) -> some View {
311+ HStack(spacing: 4) {
312+ Text("Add an App Store Connect API key with the Sales and Reports role, so Graphley can read daily downloads.")
313+ .font(Tide.text).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true)
314+ }
315+ Button {
316+ openURL(URL(string: "https://developer.apple.com/documentation/appstoreconnectapi/creating-api-keys-for-app-store-connect-api")!)
317+ } label: { HStack(spacing: 4) { Text("How to create a key"); Image(systemName: "arrow.up.right").font(.system(size: 10, weight: .semibold)) } }
318+ .buttonStyle(.tide(.quiet, size: .small)).padding(.leading, -10).padding(.top, -6)
319+
320+ ViewThatFits(in: .horizontal) {
321+ HStack(alignment: .top, spacing: 16) { keyIDField.frame(width: 240); vendorField.frame(width: 240); Spacer(minLength: 0) }
322+ VStack(alignment: .leading, spacing: 14) { keyIDField; vendorField }
323+ }
324+ TideField("Issuer ID", text: $issuerID, placeholder: "57246542-96fe-1a63-e053-0824d011072a",
325+ help: "Above the list of keys in Users and Access › Integrations.", error: err(issuerError), monospaced: true)
326+ VStack(alignment: .leading, spacing: 6) {
327+ Text("Private key").font(Tide.fieldLabel).foregroundStyle(Tide.ink)
328+ FileDropWell(file: $key, error: showErrors && key == nil ? "Choose the AuthKey_….p8 file you downloaded from App Store Connect." : nil) { file in
329+ if keyID.isEmpty, let match = file.name.firstMatch(of: /AuthKey_([A-Z0-9]{10})\.p8/) {
330+ keyID = String(match.1); keyIDHelp = "Filled in from the file name."
331+ }
332+ }
333+ Text("Apple lets you download this file only once, so keep the original somewhere safe. Graphley keeps a copy in your Keychain.")
334+ .font(Tide.caption).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
335+ }
336+ if let failure {
337+ Label(failure, systemImage: "exclamationmark.circle.fill").font(Tide.secondary).foregroundStyle(Tide.downText)
338+ .fixedSize(horizontal: false, vertical: true)
339+ }
340+ HStack(spacing: 8) {
341+ Spacer()
342+ if replacing { Button("Cancel") { self.replacing = false; failure = nil }.buttonStyle(.tide(.quiet)) }
343+ Button { save() } label: {
344+ if saving { Label("Checking with Apple…", systemImage: "hourglass") } else { Text("Save Key") }
345+ }
346+ .buttonStyle(.tide(.primary))
347+ .disabled(saving)
348+ }
349+ RowDivider()
350+ TideDisclosure("Or let your agent do it", isOpen: $agentOpen) {
351+ Text("Paste this into Claude Code, Codex or another agent connected to Graphley. It includes what you've typed above.")
352+ .font(Tide.secondary).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
353+ CopyBlock(agentPrompt(replacing: replacing), wraps: true)
354+ ToggleRow("Let agents set keys",
355+ detail: model.workspace.settings.agentsCanSetKeys ? "On. Turn it off again after your agent saves the key." : "Off. Your agent can't save keys until you turn this on.",
356+ isOn: Binding(get: { model.workspace.settings.agentsCanSetKeys }, set: { v in model.updateSettings { $0.agentsCanSetKeys = v } }))
357+ }
358+ }
359+
360+ var keyIDField: some View {
361+ TideField("Key ID", text: Binding(get: { keyID }, set: { keyID = $0.uppercased().trimmingCharacters(in: .whitespacesAndNewlines) }),
362+ placeholder: "2X9R4HXF34", help: keyIDHelp, error: err(keyIDError), monospaced: true)
363+ }
364+ var vendorField: some View {
365+ TideField("Vendor number", text: Binding(get: { vendor }, set: { vendor = $0.trimmingCharacters(in: .whitespacesAndNewlines) }),
366+ placeholder: "85123456", help: "Payments and Financial Reports, top left.", error: err(vendorError), monospaced: true)
367+ }
368+
369+ func err(_ message: String?) -> String? { showErrors ? message : nil }
370+ var keyIDError: String? { keyID.wholeMatch(of: /[A-Z0-9]{10}/) == nil ? "Key IDs are 10 letters and numbers, like 2X9R4HXF34." : nil }
371+ var issuerError: String? {
372+ let t = issuerID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
373+ return t.wholeMatch(of: /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) == nil ? "Issuer IDs look like 57246542-96fe-1a63-e053-0824d011072a." : nil
374+ }
375+ var vendorError: String? { vendor.isEmpty || !vendor.allSatisfy(\.isNumber) ? "Vendor numbers are digits only, like 85123456." : nil }
376+
377+ func agentPrompt(replacing: Bool) -> String {
378+ let path = key?.path ?? "the AuthKey_….p8 file in my Downloads folder"
379+ var lines = [
380+ "Save my App Store Connect API key in Graphley with its set_app_store_key tool.",
381+ "Key ID: \(keyID.isEmpty ? "<your key ID>" : keyID)",
382+ "Issuer ID: \(issuerID.isEmpty ? "<your issuer ID>" : issuerID.trimmingCharacters(in: .whitespaces).lowercased())",
383+ "Vendor number: \(vendor.isEmpty ? "<your vendor number>" : vendor)",
384+ "The private key is \(path). The tool reads it from the GRAPHLEY_ASC_PRIVATE_KEY environment variable of Graphley's MCP server, so restart that server with the variable set to the file's contents. Don't show the key's contents in our chat."
385+ ]
386+ if replacing { lines.append("Replace the key that's already saved.") }
387+ return lines.joined(separator: "\n")
388+ }
389+
390+ func save() {
391+ showErrors = true; failure = nil
392+ guard keyIDError == nil, issuerError == nil, vendorError == nil, let key else { return }
393+ let creds = AppStoreConnect.Credentials(keyID: keyID, issuerID: issuerID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
394+ vendorNumber: vendor, privateKey: key.pem)
395+ saving = true
396+ Task {
397+ do {
398+ try await AppStoreConnect().check(creds)
399+ try creds.save()
400+ self.key = nil; replacing = false; showErrors = false; justSaved = true
401+ model.keysChanged()
402+ } catch {
403+ failure = Self.message(for: error)
404+ }
405+ saving = false
406+ }
407+ }
408+
409+ static func message(for error: Error) -> String {
410+ if case AnalyticsError.http(let code, let body) = error {
411+ if body.localizedCaseInsensitiveContains("vendor") { return "Apple doesn't recognize this vendor number. You'll find it in Payments and Financial Reports." }
412+ if code == 401 { return "Apple didn't accept this key. Check the Key ID and Issuer ID, and make sure the .p8 file belongs to this key." }
413+ if code == 403 { return "This key can't read sales reports. Create a key with the Sales and Reports role (Finance or Admin also work)." }
414+ }
415+ if error is URLError { return "Couldn't reach Apple. Check your internet connection and try again." }
416+ if error is CryptoKitError || "\(error)".contains("CryptoKit") { return "That file isn't an App Store Connect key. Choose the AuthKey_….p8 file you downloaded from App Store Connect." }
417+ return "Apple didn't accept this key. Check the four values and try again."
418+ }
419+ }
420+
421+ /// Dashed well for the .p8: drop a file or choose one. Shows the file name, never its contents.
422+ struct FileDropWell: View {
423+ @Binding var file: AppStoreCard.KeyFile?
424+ var error: String?
425+ var onLoad: (AppStoreCard.KeyFile) -> Void
426+ @State private var targeted = false
427+ @State private var choosing = false
428+ @State private var readError: String?
429+
430+ static let p8 = UTType(filenameExtension: "p8", conformingTo: .data) ?? .data
431+
432+ var body: some View {
433+ let shownError = readError ?? error
434+ VStack(alignment: .leading, spacing: 6) {
435+ Group {
436+ if let file {
437+ HStack(spacing: 10) {
438+ Image(systemName: "doc.fill").font(.system(size: 16)).foregroundStyle(Tide.accent)
439+ VStack(alignment: .leading, spacing: 2) {
440+ Text(file.name).font(Tide.figure(13)).foregroundStyle(Tide.ink)
441+ Text("Ready to save. It goes to your Keychain.").font(Tide.caption).foregroundStyle(Tide.muted)
442+ }
443+ Spacer()
444+ Button("Replace…") { choosing = true }.buttonStyle(.tide(.quiet, size: .small))
445+ Button { self.file = nil } label: { Label("Remove file", systemImage: "xmark") }.buttonStyle(.tideIcon).help("Remove file")
446+ }
447+ .padding(.horizontal, 14)
448+ } else {
449+ HStack(spacing: 8) {
450+ Image(systemName: "key.horizontal").font(.system(size: 18)).foregroundStyle(Tide.muted)
451+ Text(targeted ? "Release to add the key" : "Drop your .p8 key file here, or").font(Tide.sans(13)).foregroundStyle(Tide.ink2)
452+ if !targeted { Button("Choose File…") { choosing = true }.buttonStyle(.tide(.quiet, size: .small)) }
453+ }
454+ .frame(maxWidth: .infinity)
455+ }
456+ }
457+ .frame(maxWidth: .infinity, minHeight: 76)
458+ .background(targeted ? Tide.accentTint : file != nil ? Tide.surface : Tide.ground, in: RoundedRectangle(cornerRadius: 10))
459+ .overlay {
460+ RoundedRectangle(cornerRadius: 10).strokeBorder(
461+ shownError != nil ? Tide.down : targeted ? Tide.accent : file != nil ? Tide.line : Tide.line2,
462+ style: StrokeStyle(lineWidth: file != nil && shownError == nil ? 1 : 1.5, dash: file == nil && !targeted && shownError == nil ? [5, 4] : []))
463+ }
464+ .onDrop(of: [.fileURL], isTargeted: $targeted) { providers in
465+ guard let provider = providers.first else { return false }
466+ _ = provider.loadObject(ofClass: URL.self) { url, _ in
467+ guard let url else { return }
468+ Task { @MainActor in load(url) }
469+ }
470+ return true
471+ }
472+ .fileImporter(isPresented: $choosing, allowedContentTypes: [Self.p8, .data]) { result in
473+ if let url = try? result.get() { load(url) }
474+ }
475+ .accessibilityElement(children: .contain)
476+ .accessibilityLabel("Choose .p8 key file")
477+ if let shownError {
478+ Label(shownError, systemImage: "exclamationmark.circle.fill").font(Tide.caption).foregroundStyle(Tide.downText)
479+ .fixedSize(horizontal: false, vertical: true)
480+ }
481+ }
482+ }
483+
484+ func load(_ url: URL) {
485+ let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }
486+ guard let data = try? Data(contentsOf: url), data.count < 4096,
487+ let pem = String(data: data, encoding: .utf8), pem.contains("-----BEGIN \("")PRIVATE KEY-----"),
488+ AppStoreConnect.Credentials.isValidPrivateKey(pem) else {
489+ readError = "That file isn't an App Store Connect key. Choose the AuthKey_….p8 file you downloaded from App Store Connect."
490+ return
491+ }
492+ readError = nil
493+ let f = AppStoreCard.KeyFile(name: url.lastPathComponent, path: (url.path as NSString).abbreviatingWithTildeInPath, pem: pem)
494+ file = f
495+ onLoad(f)
496+ }
497+ }
498+
499+ // MARK: Problems
500+
501+ /// Plain-language refresh problems, each with the button that fixes it. The raw error is under Details.
502+ struct ProblemsCard: View {
503+ @Environment(AppModel.self) private var model
504+ @State private var details = false
505+
506+ var body: some View {
507+ let failures = model.failures.sorted { $0.key < $1.key }
508+ TideCard("Last refresh needs attention", padding: 20) { StatusPill("Needs attention", .attention) } content: {
509+ VStack(alignment: .leading, spacing: 0) {
510+ ForEach(Array(failures.enumerated()), id: \.element.key) { i, f in
511+ if i > 0 { RowDivider() }
512+ let explained = Self.explain(source: f.key, error: f.value)
513+ let message = explained.0, action = explained.1
514+ HStack(alignment: .center, spacing: 12) {
515+ VStack(alignment: .leading, spacing: 2) {
516+ Text(f.key).font(Tide.rowTitle).foregroundStyle(Tide.ink)
517+ Text(message).font(Tide.secondary).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true)
518+ }
519+ Spacer()
520+ if let action {
521+ Button(action) { Task { await model.refresh() } }.buttonStyle(.tide(.secondary, size: .small)).disabled(model.refreshing)
522+ }
523+ }
524+ .padding(.vertical, 10)
525+ }
526+ }
527+ TideDisclosure("Details", isOpen: $details) {
528+ CopyBlock(failures.map { "\($0.key): \($0.value)" }.joined(separator: "\n"), wraps: true)
529+ }
530+ Text("Graphley refreshes every day at \(SettingsView.hourLabel(model.workspace.settings.refreshHour)). Change the time in Settings.")
531+ .font(Tide.caption).foregroundStyle(Tide.muted)
532+ }
533+ }
534+
535+ static func explain(source: String, error: String) -> (String, String?) {
536+ let e = error.lowercased()
537+ let apple = source.hasPrefix("App Store")
538+ if source == "iCloud sync" { return ("Couldn't share with your iPhone. Make sure this Mac is signed in to iCloud.", nil) }
539+ if e.contains("invalid_grant") || e.contains("sign in to google") { return ("Google sign-in has ended. Sign in again above.", nil) }
540+ if e.contains("(401)") && apple { return ("Apple didn't accept the App Store Connect key. Replace it above.", nil) }
541+ if e.contains("(403)") && apple { return ("The App Store Connect key can't read sales reports.", nil) }
542+ if e.contains("(403)") { return ("This Google account can't read this property anymore.", nil) }
543+ if e.contains("(429)") || e.contains("(5") { return ("\(apple ? "Apple" : "Google") was busy. Graphley will try again at the next refresh.", "Retry") }
544+ if e.contains("offline") || e.contains("timed out") || e.contains("network") || e.contains("internet") {
545+ return ("Couldn't reach \(apple ? "Apple" : "Google"). Check your internet connection.", "Retry")
546+ }
547+ return ("Something went wrong reading \(source). Graphley will try again at the next refresh.", "Retry")
548+ }
549+ }

Apps/Mac/Updates.swift added

1+ #if os(macOS)
2+ import Combine
3+ import Sparkle
4+ import SwiftUI
5+
6+ /// Sparkle updates for the Mac build downloaded from graphley.ai.
7+ /// Debug builds and builds without a feed or signing key leave the updater off.
8+ @MainActor
9+ final class AppUpdates: ObservableObject {
10+ @Published private(set) var canCheck = false
11+ private let controller: SPUStandardUpdaterController?
12+
13+ init() {
14+ #if DEBUG
15+ controller = nil
16+ #else
17+ guard Self.configured("SUFeedURL"), Self.configured("SUPublicEDKey") else {
18+ controller = nil
19+ return
20+ }
21+ let controller = SPUStandardUpdaterController(startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
22+ self.controller = controller
23+ controller.updater.publisher(for: \.canCheckForUpdates).assign(to: &$canCheck)
24+ #endif
25+ }
26+
27+ var isAvailable: Bool { controller != nil }
28+
29+ func check() { controller?.checkForUpdates(nil) }
30+
31+ private static func configured(_ key: String) -> Bool {
32+ !((Bundle.main.object(forInfoDictionaryKey: key) as? String) ?? "").isEmpty
33+ }
34+ }
35+
36+ struct CheckForUpdatesButton: View {
37+ @ObservedObject var updates: AppUpdates
38+
39+ var body: some View {
40+ Button("Check for Updates…") { updates.check() }
41+ .disabled(!updates.canCheck)
42+ }
43+ }
44+ #endif

Apps/Mac/installer-background.tiff added

Not a text file.

Apps/OwnerMac/GraphleyMac.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>com.apple.developer.associated-domains</key>
6+ <array>
7+ <string>webcredentials:projectatom.ai</string>
8+ </array>
9+ <key>com.apple.security.app-sandbox</key>
10+ <true/>
11+ <key>com.apple.security.network.client</key>
12+ <true/>
13+ </dict>
14+ </plist>

Apps/OwnerMac/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Graphley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleURLTypes</key>
22+ <array>
23+ <dict>
24+ <key>CFBundleURLName</key>
25+ <string>com.protomota.graphley.passkey-setup</string>
26+ <key>CFBundleURLSchemes</key>
27+ <array>
28+ <string>graphley</string>
29+ </array>
30+ </dict>
31+ </array>
32+ <key>CFBundleVersion</key>
33+ <string>$(CURRENT_PROJECT_VERSION)</string>
34+ <key>ITSAppUsesNonExemptEncryption</key>
35+ <false/>
36+ <key>LSApplicationCategoryType</key>
37+ <string>public.app-category.business</string>
38+ </dict>
39+ </plist>

Apps/OwnerMac/OwnerMacApp.swift added

1+ import OwnerMetricsUI
2+ import SwiftUI
3+
4+ @main
5+ struct GraphleyOwnerMacApp: App {
6+ var body: some Scene {
7+ WindowGroup("Graphley") {
8+ OwnerDashboard().frame(minWidth: 480, idealWidth: 800, minHeight: 480, idealHeight: 760)
9+ }
10+ .defaultSize(width: 800, height: 760)
11+ }
12+ }

Apps/OwnerMac/PrivacyInfo.xcprivacy added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>NSPrivacyTracking</key><false/>
6+ <key>NSPrivacyTrackingDomains</key><array/>
7+ <key>NSPrivacyCollectedDataTypes</key><array/>
8+ <key>NSPrivacyAccessedAPITypes</key><array/>
9+ </dict>
10+ </plist>

Apps/OwnerPhone/GraphleyPhone.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>com.apple.developer.associated-domains</key>
6+ <array>
7+ <string>webcredentials:projectatom.ai</string>
8+ </array>
9+ </dict>
10+ </plist>

Apps/OwnerPhone/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Graphley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleURLTypes</key>
22+ <array>
23+ <dict>
24+ <key>CFBundleURLName</key>
25+ <string>com.protomota.graphley.passkey-setup</string>
26+ <key>CFBundleURLSchemes</key>
27+ <array>
28+ <string>graphley</string>
29+ </array>
30+ </dict>
31+ </array>
32+ <key>CFBundleVersion</key>
33+ <string>$(CURRENT_PROJECT_VERSION)</string>
34+ <key>ITSAppUsesNonExemptEncryption</key>
35+ <false/>
36+ <key>UILaunchScreen</key>
37+ <dict/>
38+ <key>UISupportedInterfaceOrientations</key>
39+ <array>
40+ <string>UIInterfaceOrientationPortrait</string>
41+ </array>
42+ <key>UISupportedInterfaceOrientations~ipad</key>
43+ <array>
44+ <string>UIInterfaceOrientationPortrait</string>
45+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
46+ <string>UIInterfaceOrientationLandscapeLeft</string>
47+ <string>UIInterfaceOrientationLandscapeRight</string>
48+ </array>
49+ </dict>
50+ </plist>

Apps/OwnerPhone/OwnerPhoneApp.swift added

1+ import OwnerMetricsUI
2+ import SwiftUI
3+
4+ @main
5+ struct GraphleyOwnerPhoneApp: App {
6+ var body: some Scene {
7+ WindowGroup {
8+ OwnerDashboard()
9+ }
10+ }
11+ }

Apps/OwnerPhone/PrivacyInfo.xcprivacy added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>NSPrivacyTracking</key><false/>
6+ <key>NSPrivacyTrackingDomains</key><array/>
7+ <key>NSPrivacyCollectedDataTypes</key><array/>
8+ <key>NSPrivacyAccessedAPITypes</key><array/>
9+ </dict>
10+ </plist>

Apps/iPhone/Assets.xcassets/AccentColor.colorset/Contents.json added

1+ { "colors" : [
2+ { "color" : { "color-space" : "srgb", "components" : { "red" : "0x1D", "green" : "0x6E", "blue" : "0x8A", "alpha" : "1.000" } }, "idiom" : "universal" },
3+ { "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ], "color" : { "color-space" : "srgb", "components" : { "red" : "0x5D", "green" : "0xB6", "blue" : "0xD2", "alpha" : "1.000" } }, "idiom" : "universal" }
4+ ], "info" : { "author" : "xcode", "version" : 1 } }

Apps/iPhone/Assets.xcassets/AppIcon.appiconset/Contents.json added

1+ { "images" : [ { "filename" : "icon-1024.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } ],
2+ "info" : { "author" : "xcode", "version" : 1 } }

Apps/iPhone/Assets.xcassets/AppIcon.appiconset/icon-1024.png added

Not a text file.

Apps/iPhone/Assets.xcassets/Contents.json added

1+ { "info" : { "author" : "xcode", "version" : 1 } }

Apps/iPhone/ConnectMac.swift added

1+ import SwiftUI
2+ import UIKit
3+ import AnalyticsKit
4+ import AnalyticsUI
5+
6+ /// First run on iPhone and iPad, before any numbers arrive: how to connect Graphley for Mac, the same
7+ /// "set up your Mac" pattern as Inkspring's and OpenTalon's companion apps, with this device's iCloud status.
8+ struct ConnectMacGuide: View {
9+ @Environment(PhoneModel.self) private var model
10+ /// Opens iCloud Sync settings (a tab on iPhone, a sidebar row on iPad).
11+ let openSettings: () -> Void
12+
13+ static let downloadURL = URL(string: "https://graphley.ai/download")!
14+ private var device: String { UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone" }
15+
16+ var body: some View {
17+ VStack(alignment: .leading, spacing: 20) {
18+ VStack(alignment: .leading, spacing: 12) {
19+ TideMark(size: 64).accessibilityHidden(true)
20+ Text("Connect Graphley for Mac").font(Tide.screenTitle).foregroundStyle(Tide.ink)
21+ .accessibilityAddTraits(.isHeader)
22+ Text("Graphley for Mac fetches your Google Analytics and App Store numbers. This \(device) shows them through your private iCloud.")
23+ .font(Tide.text).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
24+ }
25+ TideCard("Set up your Mac", icon: "desktopcomputer") {
26+ VStack(alignment: .leading, spacing: 18) {
27+ step(1, "Get Graphley for Mac", "Download the free app from graphley.ai, open it and add a site or app.")
28+ Link(destination: Self.downloadURL) {
29+ Label("Get Graphley for Mac", systemImage: "arrow.down.circle")
30+ }
31+ .buttonStyle(.tide(.primary))
32+ .padding(.leading, 42)
33+ .accessibilityIdentifier("connect.macDownload")
34+ step(2, "Turn on sharing", "In Graphley on your Mac, open Settings and turn on Share with iPhone and iPad through iCloud.")
35+ step(3, "Use the same Apple Account", "Sign in to iCloud with the same Apple Account on your Mac and this \(device). Your numbers appear here after the Mac's next refresh.")
36+ }
37+ }
38+ TideCard("iCloud on this \(device)", icon: "icloud") {
39+ VStack(alignment: .leading, spacing: 10) {
40+ CloudSyncRow("Apple Account", model.cloud.accountStatus)
41+ CloudSyncRow("Numbers from your Mac", CloudSyncText.snapshotStatus(model.cloud))
42+ if let error = model.cloud.error {
43+ Text(error).font(Tide.secondary).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
44+ }
45+ ViewThatFits(in: .horizontal) {
46+ HStack(spacing: 8) { buttons }
47+ VStack(alignment: .leading, spacing: 8) { buttons }
48+ }
49+ }
50+ }
51+ Text("Graphley has no account and no server. Your keys stay in your Mac's Keychain.")
52+ .font(Tide.caption).foregroundStyle(Tide.muted)
53+ }
54+ .frame(maxWidth: 560, alignment: .leading)
55+ .accessibilityIdentifier("connectMac")
56+ }
57+
58+ @ViewBuilder private var buttons: some View {
59+ Button { Task { await model.load() } } label: {
60+ Label(model.loading ? "Checking iCloud…" : "Check Now", systemImage: "arrow.clockwise")
61+ }
62+ .buttonStyle(.tide(.secondary)).disabled(model.loading)
63+ Button("iCloud Sync Settings", action: openSettings).buttonStyle(.tide(.quiet))
64+ }
65+
66+ private func step(_ number: Int, _ title: String, _ detail: String) -> some View {
67+ HStack(alignment: .top, spacing: 12) {
68+ Text("\(number)").font(Tide.sans(15, .semibold)).foregroundStyle(Tide.accent)
69+ .frame(width: 30, height: 30).background(Tide.accent.opacity(0.12), in: Circle())
70+ .accessibilityHidden(true)
71+ VStack(alignment: .leading, spacing: 4) {
72+ Text(title).font(Tide.rowTitle).foregroundStyle(Tide.ink)
73+ Text(detail).font(Tide.secondary).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
74+ }
75+ }
76+ .accessibilityElement(children: .combine)
77+ }
78+ }

Apps/iPhone/GraphleyPhone.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>aps-environment</key>
6+ <string>production</string>
7+ <key>com.apple.developer.icloud-container-identifiers</key>
8+ <array>
9+ <string>iCloud.com.protomota.graphley</string>
10+ </array>
11+ <key>com.apple.developer.icloud-services</key>
12+ <array>
13+ <string>CloudKit</string>
14+ </array>
15+ </dict>
16+ </plist>

Apps/iPhone/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Graphley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleVersion</key>
22+ <string>$(CURRENT_PROJECT_VERSION)</string>
23+ <key>ITSAppUsesNonExemptEncryption</key>
24+ <false/>
25+ <key>NSHumanReadableCopyright</key>
26+ <string>A Project ATOM project</string>
27+ <key>UIBackgroundModes</key>
28+ <array>
29+ <string>remote-notification</string>
30+ </array>
31+ <key>UILaunchScreen</key>
32+ <dict/>
33+ <key>UISupportedInterfaceOrientations</key>
34+ <array>
35+ <string>UIInterfaceOrientationPortrait</string>
36+ </array>
37+ <key>UISupportedInterfaceOrientations~ipad</key>
38+ <array>
39+ <string>UIInterfaceOrientationPortrait</string>
40+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
41+ <string>UIInterfaceOrientationLandscapeLeft</string>
42+ <string>UIInterfaceOrientationLandscapeRight</string>
43+ </array>
44+ </dict>
45+ </plist>

Apps/iPhone/PadApp.swift added

1+ import SwiftUI
2+ import AnalyticsKit
3+ import AnalyticsUI
4+
5+ // iPad: the Mac's layout for reading. Our own sidebar rows on the left, one screen on the right,
6+ // the same Tide cards, tiles and charts as the Mac (design/DESIGN.md). Everything here is
7+ // read-only; the Mac refreshes the numbers and shares them through iCloud.
8+
9+ enum PadItem: Hashable { case overview, apps, dashboard(String), site(String), settings }
10+
11+ struct PadRootView: View {
12+ @Environment(PhoneModel.self) private var model
13+ @State private var columns: NavigationSplitViewVisibility = .all
14+
15+ var body: some View {
16+ NavigationSplitView(columnVisibility: $columns) {
17+ PadSidebar()
18+ .navigationSplitViewColumnWidth(min: 260, ideal: 290, max: 340)
19+ .toolbar(.hidden, for: .navigationBar)
20+ } detail: {
21+ PadDetail()
22+ }
23+ .navigationSplitViewStyle(.balanced)
24+ }
25+ }
26+
27+ // MARK: Sidebar
28+
29+ struct PadSidebar: View {
30+ @Environment(PhoneModel.self) private var model
31+
32+ var body: some View {
33+ VStack(alignment: .leading, spacing: 0) {
34+ HStack(spacing: 10) {
35+ TideMark(size: 30)
36+ Text("Graphley").font(Tide.display(22)).tracking(-0.3).foregroundStyle(Tide.ink)
37+ }
38+ .padding(.horizontal, 22).padding(.top, 20).padding(.bottom, 6)
39+ .accessibilityElement(children: .combine)
40+
41+ ScrollView {
42+ VStack(alignment: .leading, spacing: 2) {
43+ PadSectionLabel("Portfolio")
44+ PadSidebarRow("Overview", icon: "chart.xyaxis.line", item: .overview)
45+ PadSidebarRow("Apps", icon: "arrow.down.app", item: .apps)
46+ ForEach(model.dashboards) { d in
47+ PadSidebarRow(d.name, icon: "rectangle.3.group", item: .dashboard(d.id))
48+ }
49+ if !model.sites.isEmpty {
50+ PadSectionLabel("Sites")
51+ // Same order as the Mac's sidebar, which the user sets by dragging there.
52+ ForEach(model.sites) { site in
53+ PadSidebarRow(site.name, dot: Tide.color(for: site),
54+ count: model.total(.users, [site.id], days: model.range), item: .site(site.id))
55+ }
56+ }
57+ PadSectionLabel("Graphley")
58+ PadSidebarRow("Settings", icon: "gearshape", item: .settings)
59+ }
60+ .padding(.horizontal, 12).padding(.bottom, 12)
61+ }
62+ PadSyncStatus()
63+ }
64+ .background(Tide.ground)
65+ }
66+ }
67+
68+ struct PadSectionLabel: View {
69+ let text: String
70+ init(_ text: String) { self.text = text }
71+ var body: some View {
72+ Text(text.uppercased()).font(Tide.sectionLabel).tracking(0.8).foregroundStyle(Tide.muted)
73+ .padding(.leading, 12).padding(.top, 18).padding(.bottom, 6)
74+ .accessibilityAddTraits(.isHeader)
75+ }
76+ }
77+
78+ struct PadSidebarRow: View {
79+ let title: String, icon: String?, dot: Color?, count: Double?, item: PadItem
80+ @Environment(PhoneModel.self) private var model
81+ @Environment(\.colorScheme) private var scheme
82+ @State private var hover = false
83+
84+ init(_ title: String, icon: String? = nil, dot: Color? = nil, count: Double? = nil, item: PadItem) {
85+ self.title = title; self.icon = icon; self.dot = dot; self.count = count; self.item = item
86+ }
87+
88+ var body: some View {
89+ let selected = model.padSelection == item
90+ Button { model.padSelection = item } label: {
91+ HStack(spacing: 10) {
92+ if let icon {
93+ Image(systemName: icon).font(.system(size: 16, weight: .medium)).frame(width: 22)
94+ .foregroundStyle(selected ? Tide.accentInk : Tide.muted)
95+ } else if let dot {
96+ // On the selected row the dot turns light, so a teal site stays visible on the teal fill.
97+ Circle().fill(selected ? Tide.accentInk : dot).frame(width: 9, height: 9).frame(width: 22)
98+ }
99+ Text(title).font(Tide.sans(16, .medium)).lineLimit(1).truncationMode(.tail)
100+ .foregroundStyle(selected ? Tide.accentInk : Tide.ink)
101+ Spacer(minLength: 4)
102+ if let count {
103+ Text(Tide.number(count)).font(Tide.figure(13))
104+ .foregroundStyle(selected ? Tide.accentInk.opacity(0.75) : Tide.muted)
105+ }
106+ }
107+ .padding(.horizontal, 12)
108+ .frame(height: 44)
109+ .background(selected ? Tide.fill : hover ? (scheme == .dark ? Tide.surface2 : Tide.sunk) : .clear, in: RoundedRectangle(cornerRadius: 10))
110+ .contentShape(RoundedRectangle(cornerRadius: 10))
111+ }
112+ .buttonStyle(.plain)
113+ .onHover { hover = $0 }
114+ .accessibilityAddTraits(selected ? .isSelected : [])
115+ }
116+ }
117+
118+ /// Bottom of the sidebar: when the Mac last shared numbers, with a button to check iCloud again.
119+ struct PadSyncStatus: View {
120+ @Environment(PhoneModel.self) private var model
121+ var body: some View {
122+ HStack(spacing: 10) {
123+ Circle().fill(dotColor).frame(width: 7, height: 7)
124+ VStack(alignment: .leading, spacing: 2) {
125+ Text(headline).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink).lineLimit(1)
126+ Text(detail).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(2)
127+ }
128+ Spacer(minLength: 4)
129+ Button { Task { await model.load() } } label: {
130+ if model.loading { ProgressView() } else { Label("Check iCloud", systemImage: "arrow.clockwise") }
131+ }
132+ .buttonStyle(.tideIcon)
133+ .disabled(model.loading)
134+ .accessibilityLabel("Check iCloud for new numbers")
135+ }
136+ .padding(.leading, 18).padding(.trailing, 10).padding(.vertical, 12)
137+ .overlay(alignment: .top) { Rectangle().fill(Tide.line).frame(height: 1) }
138+ }
139+
140+ var stale: Bool { model.snapshot.map { Date.now.timeIntervalSince($0.refreshedAt) > 36 * 3600 } ?? false }
141+ var dotColor: Color { model.error != nil ? Tide.down : stale || model.snapshot == nil ? Tide.attention : Tide.up }
142+ var headline: String { model.snapshot == nil ? "Waiting for your Mac" : "Synced from your Mac" }
143+ var detail: String {
144+ if model.snapshot == nil, let e = model.cloud.error { return e }
145+ guard let s = model.snapshot else { return "Through iCloud" }
146+ return "Updated \(s.refreshedAt.formatted(.relative(presentation: .named)))"
147+ }
148+ }
149+
150+ // MARK: Detail
151+
152+ struct PadDetail: View {
153+ @Environment(PhoneModel.self) private var model
154+
155+ var body: some View {
156+ NavigationStack {
157+ TourScrollView("pad") {
158+ VStack(alignment: .leading, spacing: 16) {
159+ if model.snapshot != nil, let e = model.error { Banner(text: e, kind: .error) }
160+ if let s = model.snapshot, Date.now.timeIntervalSince(s.refreshedAt) > 36 * 3600 {
161+ Banner(text: "These numbers are from \(s.refreshedAt.formatted(.relative(presentation: .named))). Open Graphley on your Mac to refresh.", kind: .attention)
162+ }
163+ if model.snapshot == nil && model.padSelection != .settings { PadWaiting() } else { screen }
164+ }
165+ .padding(.horizontal, 32).padding(.top, 8).padding(.bottom, 32)
166+ .frame(maxWidth: 1180, alignment: .leading)
167+ .frame(maxWidth: .infinity, alignment: .leading)
168+ }
169+ .id(model.padSelection)
170+ .refreshable { await model.load() }
171+ .background(Tide.surface)
172+ .toolbarBackground(.hidden, for: .navigationBar)
173+ .navigationBarTitleDisplayMode(.inline)
174+ }
175+ }
176+
177+ @ViewBuilder var screen: some View {
178+ switch model.padSelection {
179+ case .overview: PadOverview()
180+ case .apps: PadAppStore()
181+ case .dashboard(let id): PadDashboard(dashboardID: id)
182+ case .site(let id): PadSite(siteID: id)
183+ case .settings: SyncSettingsContent()
184+ }
185+ }
186+ }
187+
188+ struct PadWaiting: View {
189+ @Environment(PhoneModel.self) private var model
190+ var body: some View {
191+ ConnectMacGuide { model.padSelection = .settings }
192+ .frame(maxWidth: .infinity).padding(.top, 48)
193+ }
194+ }
195+
196+ /// The 7 / 30 / 90 day pill, bound to the iPad's range.
197+ struct PadRange: View {
198+ @Environment(PhoneModel.self) private var model
199+ var body: some View {
200+ @Bindable var model = model
201+ RangeSelector(selection: $model.range)
202+ }
203+ }
204+
205+ /// Lays out side by side when there is room, stacked otherwise (portrait, split view).
206+ struct PadPair<First: View, Second: View>: View {
207+ let wide: Bool, secondWidth: CGFloat
208+ let first: First, second: Second
209+ init(wide: Bool, secondWidth: CGFloat = 340, @ViewBuilder first: () -> First, @ViewBuilder second: () -> Second) {
210+ self.wide = wide; self.secondWidth = secondWidth; self.first = first(); self.second = second()
211+ }
212+ var body: some View {
213+ if wide {
214+ HStack(alignment: .top, spacing: 16) { first.layoutPriority(1); second.frame(width: secondWidth) }
215+ } else {
216+ VStack(alignment: .leading, spacing: 16) { first; second }
217+ }
218+ }
219+ }
220+
221+ /// Measures the screen's width so cards can sit side by side in landscape.
222+ struct WidthReader: ViewModifier {
223+ @Binding var width: CGFloat
224+ func body(content: Content) -> some View {
225+ content.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
226+ }
227+ }
228+
229+ // MARK: Overview
230+
231+ struct PadOverview: View {
232+ @Environment(PhoneModel.self) private var model
233+ @State private var width: CGFloat = 900
234+
235+ var body: some View {
236+ let n = model.range
237+ VStack(alignment: .leading, spacing: 16) {
238+ ScreenHeading("Overview", subtitle: subtitle) { PadRange() }
239+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: width > 760 ? tiles.count : 2), spacing: 12) {
240+ ForEach(tiles, id: \.0) { m, label in
241+ KPITile(label, value: model.total(m, days: n), previous: model.total(m, days: n, offset: n), footer: "vs previous \(n) days")
242+ }
243+ }
244+ TideCard("Daily visitors by site", subtitle: "Stacked. Touch a day to read it.") {
245+ StackedChart(days: model.days, series: stackedSeries).frame(height: 340)
246+ }
247+ PadPair(wide: width > 860 && !model.apps.isEmpty) {
248+ TideCard("Every site", subtitle: "Last \(n) days vs the \(n) before. Tap a site to open it.") { PadSiteTable() }
249+ } second: {
250+ if !model.apps.isEmpty {
251+ TideCard("Every app", subtitle: "App Store and Mac website downloads, last \(n) days. Tap an app to open Apps.") {
252+ Button { model.padSelection = .apps } label: {
253+ BarList(model.apps.map { ($0.shortName, model.appTotal($0, days: n)) }.sorted { $0.1 > $1.1 })
254+ }
255+ .buttonStyle(.plain)
256+ .accessibilityHint("Opens Apps")
257+ }
258+ }
259+ }
260+ }
261+ .modifier(WidthReader(width: $width))
262+ }
263+
264+ var subtitle: String {
265+ let sites = model.sites.count, apps = model.apps.count
266+ var s = "\(sites) \(sites == 1 ? "site" : "sites") and \(apps) \(apps == 1 ? "app" : "apps")"
267+ if let last = model.points.map(\.day).max(), let date = PadDay.date(last) {
268+ s += " · data through \(date.formatted(.dateTime.month(.abbreviated).day()))"
269+ }
270+ return s
271+ }
272+
273+ var tiles: [(Metric, String)] {
274+ var t: [(Metric, String)] = [(.users, "Visitors"), (.sessions, "Sessions"), (.pageViews, "Page views")]
275+ if !model.apps.isEmpty { t.append((.appDownloads, "App Store downloads")) }
276+ return t
277+ }
278+
279+ /// Top five sites plus one "Other sites" band, so colors never repeat.
280+ var stackedSeries: [StackedChart.Series] {
281+ let n = model.range
282+ let ranked = model.sites.sorted { model.total(.users, [$0.id], days: n) > model.total(.users, [$1.id], days: n) }
283+ 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)) }
284+ let rest = ranked.dropFirst(5).map(\.id)
285+ if !rest.isEmpty {
286+ series.append(.init(id: "other", name: "Other sites", color: Tide.other, values: model.series(.users, Set(rest), days: n)))
287+ }
288+ return series
289+ }
290+ }
291+
292+ struct PadSiteTable: View {
293+ @Environment(PhoneModel.self) private var model
294+ var body: some View {
295+ let n = model.range
296+ VStack(spacing: 0) {
297+ HStack(spacing: 12) {
298+ Text("Site").frame(maxWidth: .infinity, alignment: .leading)
299+ Text("Trend").frame(width: 80, alignment: .leading)
300+ Text("Visitors").frame(width: 72, alignment: .trailing)
301+ Text("Change").frame(width: 60, alignment: .trailing)
302+ Text("Page views").frame(width: 84, alignment: .trailing)
303+ }
304+ .font(Tide.caption).foregroundStyle(Tide.muted)
305+ .padding(.horizontal, 10).padding(.bottom, 8)
306+ RowDivider()
307+ ForEach(model.sites.sorted { model.total(.users, [$0.id], days: n) > model.total(.users, [$1.id], days: n) }) { s in
308+ PadSiteRow(site: s)
309+ }
310+ }
311+ }
312+ }
313+
314+ struct PadSiteRow: View {
315+ let site: Site
316+ @Environment(PhoneModel.self) private var model
317+ @State private var hover = false
318+ var body: some View {
319+ let n = model.range
320+ let cur = model.total(.users, [site.id], days: n)
321+ Button { model.padSelection = .site(site.id) } label: {
322+ HStack(spacing: 12) {
323+ HStack(spacing: 9) {
324+ Circle().fill(Tide.color(for: site)).frame(width: 9, height: 9)
325+ Text(site.name).font(Tide.sans(15, .medium)).foregroundStyle(Tide.ink).lineLimit(1)
326+ }
327+ .frame(maxWidth: .infinity, alignment: .leading)
328+ Sparkline(model.series(.users, [site.id], days: n), color: Tide.color(for: site))
329+ Text(Tide.number(cur)).font(Tide.figure(14)).foregroundStyle(Tide.ink).frame(width: 72, alignment: .trailing)
330+ DeltaLabel(current: cur, previous: model.total(.users, [site.id], days: n, offset: n)).frame(width: 60, alignment: .trailing)
331+ Text(Tide.number(model.total(.pageViews, [site.id], days: n))).font(Tide.figure(14)).foregroundStyle(Tide.ink2).frame(width: 84, alignment: .trailing)
332+ }
333+ .padding(.horizontal, 10).frame(height: 46)
334+ .background(hover ? Tide.sunk : .clear, in: RoundedRectangle(cornerRadius: 8))
335+ .contentShape(Rectangle())
336+ }
337+ .buttonStyle(.plain)
338+ .onHover { hover = $0 }
339+ .accessibilityLabel("\(site.name), \(Tide.number(cur)) visitors")
340+ .accessibilityHint("Opens the site")
341+ }
342+ }
343+
344+ // MARK: Site
345+
346+ struct PadSite: View {
347+ @Environment(PhoneModel.self) private var model
348+ @Environment(\.openURL) private var openURL
349+ let siteID: String
350+ @State private var metric: Metric = .users
351+ @State private var width: CGFloat = 900
352+
353+ static let eventNames = ["mac_installer_download": "Mac downloads", "download_click_mac": "Mac downloads",
354+ "app_store_click": "App Store clicks", "download_click_ios": "App Store clicks",
355+ "source_click": "Source clicks", "source_download": "Source downloads",
356+ "newsletter_click": "Newsletter clicks", "book_call": "Calls booked", "generate_lead": "Leads"]
357+
358+ var body: some View {
359+ if let site = model.sites.first(where: { $0.id == siteID }) {
360+ let n = model.range
361+ let pages = model.points.filter { $0.subject == siteID && ($0.breakdown?.hasPrefix("page:") ?? false) }
362+ .sorted { $0.value > $1.value }.prefix(8).map { (String($0.breakdown!.dropFirst(5)), $0.value) }
363+ VStack(alignment: .leading, spacing: 16) {
364+ ScreenHeading(site.name, subtitle: site.url?.host() ?? "Google Analytics 4") {
365+ HStack(spacing: 6) {
366+ if let url = site.url {
367+ Button { openURL(url) } label: { Label("Open \(url.host() ?? site.name)", systemImage: "arrow.up.right.square") }
368+ .buttonStyle(.tideIcon)
369+ .accessibilityLabel("Open \(url.host() ?? site.name)")
370+ }
371+ PadRange()
372+ }
373+ }
374+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: width > 760 ? 4 : 2), spacing: 12) {
375+ ForEach([Metric.users, .newUsers, .sessions, .pageViews], id: \.self) { m in
376+ Button { withAnimation(.easeOut(duration: 0.15)) { metric = m } } label: {
377+ KPITile(m.title, value: model.total(m, [siteID], days: n), previous: model.total(m, [siteID], days: n, offset: n),
378+ footer: "vs previous \(n) days", selected: metric == m)
379+ }
380+ .buttonStyle(.plain)
381+ }
382+ }
383+ PadPair(wide: width > 860) {
384+ TideCard("\(metric.title) per day", subtitle: "Tap a number above to switch.") {
385+ let values = model.series(metric, [siteID], days: n)
386+ TrendChart(days: model.days, values: values, color: Tide.color(for: site), label: metric.title).frame(height: 360)
387+ if values.allSatisfy({ $0 == 0 }) {
388+ Text("No \(metric.title.lowercased()) in the last \(n) days.").font(Tide.secondary).foregroundStyle(Tide.muted)
389+ }
390+ }
391+ } second: {
392+ TideCard("Top pages", subtitle: "Page views, last 30 days") {
393+ if pages.isEmpty { Text("No page views recorded yet.").font(Tide.secondary).foregroundStyle(Tide.muted) }
394+ else { BarList(Array(pages)) }
395+ }
396+ }
397+ let events = keyEvents(n)
398+ if !events.isEmpty {
399+ TideCard("Key events", subtitle: "Last \(n) days") { BarList(events) }
400+ }
401+ }
402+ .modifier(WidthReader(width: $width))
403+ }
404+ }
405+
406+ func keyEvents(_ n: Int) -> [(String, Double)] {
407+ let days = Set(DayKey.lastDays(n))
408+ var totals: [String: Double] = [:]
409+ for p in model.points where p.subject == siteID && p.metric == .keyEvent && days.contains(p.day) {
410+ guard let e = p.event else { continue }
411+ totals[Self.eventNames[e] ?? e, default: 0] += p.value
412+ }
413+ return totals.filter { $0.value > 0 }.sorted { $0.value > $1.value }.map { ($0.key, $0.value) }
414+ }
415+ }
416+
417+ // MARK: App Store
418+
419+ struct PadAppStore: View {
420+ @Environment(PhoneModel.self) private var model
421+ @State private var width: CGFloat = 900
422+
423+ static func platformName(_ raw: String) -> String {
424+ let p = raw.hasPrefix("platform:") ? String(raw.dropFirst(9)) : raw
425+ switch p.lowercased() {
426+ case "iphone": return "iPhone"
427+ case "ipad": return "iPad"
428+ case "desktop", "mac": return "Mac"
429+ case "apple vision", "vision", "apple vision pro": return "Apple Vision Pro"
430+ case "apple tv", "appletv": return "Apple TV"
431+ default: return p
432+ }
433+ }
434+
435+ var body: some View {
436+ let n = model.range
437+ let platforms = Set(model.points.filter { $0.metric == .appDownloads }.compactMap(\.breakdown)).sorted()
438+ VStack(alignment: .leading, spacing: 16) {
439+ ScreenHeading("Apps", subtitle: "App Store downloads from App Store Connect, and Mac installers from each app's website.") { PadRange() }
440+ if model.apps.isEmpty {
441+ TideCard {
442+ 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.")
443+ }
444+ } else {
445+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: min(model.apps.count, width > 760 ? 4 : 2)), spacing: 12) {
446+ ForEach(model.apps) { app in
447+ KPITile(app.shortName, value: model.appTotal(app, days: n),
448+ previous: model.appTotal(app, days: n, offset: n), footer: "vs previous \(n) days")
449+ }
450+ }
451+ TideCard("Downloads per day by platform", subtitle: "All apps") {
452+ StackedChart(days: model.days, series: platforms.enumerated().map { i, p in
453+ let byDay = Dictionary(grouping: model.points.filter { $0.metric == .appDownloads && $0.breakdown == p }, by: \.day).mapValues { $0.reduce(0) { $0 + $1.value } }
454+ return .init(id: p, name: Self.platformName(p), color: Tide.series[i % Tide.series.count], values: model.days.map { byDay[$0] ?? 0 })
455+ }, bars: true).frame(height: 380)
456+ }
457+ TideCard("Every app", subtitle: "Last \(n) days") {
458+ Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 12) {
459+ GridRow {
460+ Text("App"); Text("App Store").gridColumnAlignment(.trailing); Text("Mac (website)").gridColumnAlignment(.trailing)
461+ Text("Redownloads").gridColumnAlignment(.trailing); Text("Rating").gridColumnAlignment(.trailing)
462+ }
463+ .font(Tide.caption).foregroundStyle(Tide.muted)
464+ ForEach(model.apps) { app in
465+ let store = app.hasAppStoreListing ? model.total(.appDownloads, [app.id], days: n) : nil
466+ GridRow {
467+ VStack(alignment: .leading, spacing: 2) {
468+ Text(app.shortName).font(Tide.sans(15, .medium)).foregroundStyle(Tide.ink)
469+ Text((app.platforms ?? []).joined(separator: " · ")).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1)
470+ }
471+ .frame(maxWidth: .infinity, alignment: .leading)
472+ Text(store.map(Tide.number) ?? "–").font(Tide.figure(14)).foregroundStyle(Tide.ink)
473+ Text(website(app, n).map(Tide.number) ?? "–").font(Tide.figure(14)).foregroundStyle(Tide.ink)
474+ Text(app.hasAppStoreListing ? Tide.number(model.total(.appRedownloads, [app.id], days: n)) : "–").font(Tide.figure(14)).foregroundStyle(Tide.ink2)
475+ Text(rating(app.id)).font(Tide.figure(14)).foregroundStyle(Tide.ink2)
476+ }
477+ }
478+ }
479+ }
480+ }
481+ }
482+ .modifier(WidthReader(width: $width))
483+ }
484+
485+ /// Mac installer downloads from the app's website, or nil when it has no website download.
486+ func website(_ app: StoreApp, _ n: Int) -> Double? {
487+ model.points.websiteDownloads(app, days: model.days)?.reduce(0, +)
488+ }
489+
490+ func rating(_ id: String) -> String {
491+ 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 "–" }
492+ return r.value.formatted(.number.precision(.fractionLength(1))) + " ★"
493+ }
494+ }
495+
496+ // MARK: Dashboards
497+
498+ struct PadDashboard: View {
499+ @Environment(PhoneModel.self) private var model
500+ let dashboardID: String
501+ @State private var width: CGFloat = 900
502+
503+ var body: some View {
504+ if let dash = model.dashboards.first(where: { $0.id == dashboardID }) {
505+ VStack(alignment: .leading, spacing: 16) {
506+ ScreenHeading(dash.name, subtitle: "Change widgets from your agent on the Mac.")
507+ if dash.widgets.isEmpty {
508+ 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”.") }
509+ }
510+ DashboardBoard(data: model.portfolio, dashboard: dash, compact: width < 700)
511+ }
512+ .modifier(WidthReader(width: $width))
513+ }
514+ }
515+ }
516+
517+ enum PadDay {
518+ nonisolated(unsafe) static let formatter: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }()
519+ static func date(_ s: String) -> Date? { formatter.date(from: s) }
520+ }

Apps/iPhone/PhoneApp.swift added

1+ import SwiftUI
2+ import AnalyticsKit
3+ import 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
9+ struct 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.
31+ struct 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+
45+ enum PhoneTab: Hashable { case today, dashboards, sites, apps, settings }
46+
47+ struct 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.
62+ final 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
77+ final 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+
190+ struct 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.
234+ struct 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+
249+ struct 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+
273+ struct 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+
285+ struct 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.
309+ struct 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+
336+ struct 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.
369+ struct 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.
418+ struct 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.
428+ struct 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+
443+ enum TourAnchor: Hashable { case top, bottom, section(String) }
444+ struct 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.
448+ struct 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
471+ extension 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.
579+ struct 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+
620+ struct 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+ }

Apps/iPhone/PrivacyInfo.xcprivacy added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <!-- Graphley collects nothing and tracks nobody. Numbers stay on the user's devices and their own iCloud. -->
4+ <plist version="1.0">
5+ <dict>
6+ <key>NSPrivacyTracking</key>
7+ <false/>
8+ <key>NSPrivacyTrackingDomains</key>
9+ <array/>
10+ <key>NSPrivacyCollectedDataTypes</key>
11+ <array/>
12+ <key>NSPrivacyAccessedAPITypes</key>
13+ <array>
14+ <dict>
15+ <!-- WorkspaceStore.lastModified reads the modification date of the app's own workspace files. -->
16+ <key>NSPrivacyAccessedAPIType</key>
17+ <string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
18+ <key>NSPrivacyAccessedAPITypeReasons</key>
19+ <array>
20+ <string>C617.1</string>
21+ </array>
22+ </dict>
23+ </array>
24+ </dict>
25+ </plist>

Apps/iPhone/SyncSettings.swift added

1+ import SwiftUI
2+ import AnalyticsKit
3+ import AnalyticsUI
4+
5+ /// Settings on the iPhone (a tab) and the iPad (a sidebar row): the house iCloud Sync and Diagnostics
6+ /// sections, copied from Inkspring's iPhone settings, in Tide cards.
7+ struct PhoneSettingsView: View {
8+ @Environment(PhoneModel.self) private var model
9+ var body: some View {
10+ NavigationStack {
11+ ScrollView { SyncSettingsContent(showsHeading: false).padding(16) }
12+ .refreshable { await model.load() }
13+ .background(Tide.ground)
14+ .navigationTitle("Settings")
15+ }
16+ }
17+ }
18+
19+ struct SyncSettingsContent: View {
20+ @Environment(PhoneModel.self) private var model
21+ var showsHeading = true
22+
23+ var body: some View {
24+ VStack(alignment: .leading, spacing: 16) {
25+ if showsHeading { ScreenHeading("Settings", subtitle: "How this device gets your numbers from your Mac.") }
26+ TideCard("iCloud Sync", subtitle: "Your Mac puts a copy of the numbers in your private iCloud. This device reads it.", icon: "icloud") {
27+ CloudSyncSection(status: model.cloud, busy: model.loading,
28+ missingMessage: "iCloud has no numbers from your Mac yet. Open Graphley on your Mac and check Settings → iPhone and iPad.") {
29+ Task { await model.load() }
30+ }
31+ }
32+ TideCard("Diagnostics", icon: "stethoscope") {
33+ CloudDiagnosticsSection(status: model.cloud)
34+ }
35+ TideCard("About", icon: "info.circle") {
36+ Text("Graphley \(Self.version)").font(Tide.rowTitle).foregroundStyle(Tide.ink)
37+ .accessibilityIdentifier("settingsAppVersion")
38+ Text("Free and open source, public domain (Unlicense). Graphley has no server: your numbers stay in your private iCloud.")
39+ .font(Tide.secondary).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true)
40+ HStack(spacing: 16) {
41+ Link("graphley.ai", destination: URL(string: "https://graphley.ai")!)
42+ }
43+ .font(Tide.secondary).tint(Tide.accent)
44+ }
45+ }
46+ .task { if model.cloud.lastCheck == nil { await model.load() } }
47+ }
48+
49+ static var version: String {
50+ let info = Bundle.main.infoDictionary ?? [:]
51+ return "\(info["CFBundleShortVersionString"] as? String ?? "?") (\(info["CFBundleVersion"] as? String ?? "?"))"
52+ }
53+ }

LICENSE added

1+ This is free and unencumbered software released into the public domain.
2+
3+ Anyone is free to copy, modify, publish, use, compile, sell, or
4+ distribute this software, either in source code form or as a compiled
5+ binary, for any purpose, commercial or non-commercial, and by any
6+ means.
7+
8+ In jurisdictions that recognize copyright laws, the author or authors
9+ of this software dedicate any and all copyright interest in the
10+ software to the public domain. We make this dedication for the benefit
11+ of the public at large and to the detriment of our heirs and
12+ successors. We intend this dedication to be an overt act of
13+ relinquishment in perpetuity of all present and future rights to this
14+ software under copyright law.
15+
16+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22+ OTHER DEALINGS IN THE SOFTWARE.
23+
24+ For more information, please refer to <https://unlicense.org>

Package.swift added

1+ // swift-tools-version: 6.0
2+ import PackageDescription
3+
4+ let package = Package(
5+ name: "Graphley",
6+ platforms: [.macOS(.v14), .iOS(.v17)],
7+ products: [
8+ .library(name: "OwnerMetricsKit", targets: ["OwnerMetricsKit"]),
9+ .library(name: "OwnerMetricsUI", targets: ["OwnerMetricsUI"]),
10+ ],
11+ targets: [
12+ .target(name: "OwnerMetricsKit"),
13+ .target(name: "OwnerMetricsUI", dependencies: ["OwnerMetricsKit"]),
14+ .testTarget(name: "OwnerMetricsKitTests", dependencies: ["OwnerMetricsKit"]),
15+ ]
16+ )

README.md added

1+ # Graphley
2+
3+ Graphley is a private owner dashboard for aggregate Project ATOM website and app counts.
4+
5+ - The Mac, iPhone and iPad read only the fixed Project ATOM first-party endpoint. Sign-in is passkeys only (webcredentials for projectatom.ai): no passwords or pasted tokens. The first passkey comes from a one-time `graphley://passkey-setup` link minted on the server (see protomota-com `docs/visitor-odometer.md`); add a second passkey in the app as recovery. The app keeps only the sign-in session in the device-only Keychain, not in the app bundle, iCloud or analytics.
6+ - Explore totals, UTC daily trends and counts by website or app for 7, 30 or 90 days. Missing days within a reported series are zero. Empty data means no new first-party reports were received; historical Google numbers are not imported.
7+ - The private build does not include Google sign-in or reporting, the old public updater, or the older iCloud sync and MCP entry points. Old local files and CloudKit records are not read, changed or deleted.
8+ - No public Mac distribution or App Store submission. Before any TestFlight upload, verify the app is owner-only and old automatic distribution is disabled. See [Releasing](RELEASING.md).
9+
10+ For local development, run `swift test` for fixture-based contract tests and `xcodegen generate` to create the Mac and iOS Xcode targets. Never use a real session or setup link in tests.

RELEASING.md added

1+ # Graphley private release checklist
2+
3+ Graphley has no public release path. Mac builds are local for development only. Do not ship a direct-download bundle, Sparkle update, public TestFlight link, external group, public App Store listing, or review submission.
4+
5+ ## iPhone and iPad internal TestFlight only
6+
7+ 1. Verify in App Store Connect that the owner is the only intended internal tester and that no existing group, public link or automatic distribution can give this build to other users. Confirm any previously public listing/builds separately; this source change cannot retire them.
8+ 2. Verify the release branch and build exactly match the staged scope. Ensure Project ATOM serves the passkey API and `/.well-known/apple-app-site-association`, the App IDs have the Associated Domains capability, and the provisioning profiles include `webcredentials:projectatom.ai`. The setup secret and setup links never go in release configuration, CI, source code, screenshots or fixture logs.
9+ 3. After the audience check and user authorization, explicitly dispatch TestFlight with owner audience verified (or run the script locally with `GRAPHLEY_OWNER_TESTFLIGHT_VERIFIED=1`). The script uploads only; group assignment is an intentional, separate owner-only action. A feature build alone does not authorize this.
10+ 4. Verify the processed build’s audience and manually assign only to the verified owner-only internal group. Confirm on the owner’s iPhone/iPad that passkey sign-in opens the counts and the session remains device-local. No live verification or audience changes are implied by local builds or fixture tests.
11+
12+ Historical public workflows and Google/CloudKit code are retained in Git history. The owner build neither migrates nor deletes the old data.

Sources/AnalyticsKit/AppStore.swift added

1+ import Foundation
2+ import CryptoKit
3+
4+ /// App Store Connect sales reports: daily first downloads and redownloads per app and device.
5+ /// Needs an App Store Connect API key (Sales and Reports role) saved in the Keychain.
6+ public struct AppStoreConnect: Sendable {
7+ static let downloadTypes: Set<String> = ["1", "1F", "1T", "1E", "F1"]
8+ static let redownloadTypes: Set<String> = ["3", "3F", "3T", "F3"]
9+ let session: URLSession
10+ public init(session: URLSession = .shared) { self.session = session }
11+
12+ public var isConfigured: Bool {
13+ [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStorePrivateKey, .appStoreVendorNumber].allSatisfy(Keychain.has)
14+ }
15+
16+ /// Pulls each missing day (Apple publishes a day's report the next morning, Pacific time).
17+ public func daily(apps: [StoreApp], days: [String]) async throws -> [DataPoint] {
18+ guard isConfigured else { throw AnalyticsError.notSignedIn("App Store Connect") }
19+ let listed = apps.filter(\.hasAppStoreListing)
20+ let ids = Set(listed.map(\.id))
21+ let desktop = Dictionary(uniqueKeysWithValues: listed.map { ($0.id, $0.desktopCountsAs ?? "Mac") })
22+ var points: [DataPoint] = []
23+ for day in days {
24+ // Apple 404s a day it hasn't published yet: skip it (never stored as zero) so the next run asks again.
25+ guard let tsv = try await report(day: day) else { continue }
26+ points += Self.parse(tsv: tsv, day: day, appIDs: ids, desktop: desktop)
27+ }
28+ return points
29+ }
30+
31+ /// The four parts of an App Store Connect API key. The app's form builds one to check it before saving.
32+ public struct Credentials: Sendable {
33+ public var keyID, issuerID, vendorNumber, privateKey: String
34+ public init(keyID: String, issuerID: String, vendorNumber: String, privateKey: String) {
35+ self.keyID = keyID; self.issuerID = issuerID; self.vendorNumber = vendorNumber; self.privateKey = privateKey
36+ }
37+ /// The saved key, if all four parts are in the Keychain.
38+ public static var saved: Credentials? {
39+ guard let k = Keychain.get(.appStoreKeyID), let i = Keychain.get(.appStoreIssuerID),
40+ let v = Keychain.get(.appStoreVendorNumber), let p = Keychain.get(.appStorePrivateKey) else { return nil }
41+ return Credentials(keyID: k, issuerID: i, vendorNumber: v, privateKey: p)
42+ }
43+ public func save() throws {
44+ try Keychain.set(keyID, for: .appStoreKeyID); try Keychain.set(issuerID, for: .appStoreIssuerID)
45+ try Keychain.set(vendorNumber, for: .appStoreVendorNumber); try Keychain.set(privateKey, for: .appStorePrivateKey)
46+ }
47+ public static func remove() {
48+ [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStoreVendorNumber, .appStorePrivateKey].forEach(Keychain.remove)
49+ }
50+ /// True when the text is a PEM private key that CryptoKit can sign with.
51+ public static func isValidPrivateKey(_ pem: String) -> Bool { (try? P256.Signing.PrivateKey(pemRepresentation: pem)) != nil }
52+ }
53+
54+ /// Asks Apple for one recent day's sales report with these credentials. Throws `AnalyticsError.http`
55+ /// (401 bad key, 403 wrong role) or a URL error. A day without sales counts as success.
56+ public func check(_ credentials: Credentials) async throws {
57+ _ = try await report(day: DayKey.lastDays(2).first ?? "", credentials: credentials)
58+ }
59+
60+ func report(day: String, credentials: Credentials? = nil) async throws -> String? {
61+ var c = URLComponents(string: "https://api.appstoreconnect.apple.com/v1/salesReports")!
62+ c.queryItems = [
63+ .init(name: "filter[frequency]", value: "DAILY"), .init(name: "filter[reportType]", value: "SALES"),
64+ .init(name: "filter[reportSubType]", value: "SUMMARY"), .init(name: "filter[version]", value: "1_1"),
65+ .init(name: "filter[vendorNumber]", value: credentials?.vendorNumber ?? Keychain.get(.appStoreVendorNumber)),
66+ .init(name: "filter[reportDate]", value: day)
67+ ]
68+ var r = URLRequest(url: c.url!)
69+ r.setValue("Bearer \(try token(credentials: credentials))", forHTTPHeaderField: "Authorization")
70+ r.setValue("application/a-gzip", forHTTPHeaderField: "Accept")
71+ let (data, response) = try await session.data(for: r)
72+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
73+ if code == 404 { return nil } // no sales that day, or not published yet
74+ guard code == 200 else { throw AnalyticsError.http(code, String(decoding: data, as: UTF8.self)) }
75+ return String(decoding: try Gzip.inflate(data), as: UTF8.self)
76+ }
77+
78+ /// Apple's Device column as Graphley shows it: Desktop is a Mac (or, for an iOS-only app like Jotley, the
79+ /// iPhone app running on an Apple Silicon Mac), Apple Vision is Vision Pro.
80+ public static func platform(device: String, desktopCountsAs: String = "Mac") -> String {
81+ switch device.trimmingCharacters(in: .whitespaces).lowercased() {
82+ case "iphone", "ipod", "ipod touch": "iPhone"
83+ case "ipad": "iPad"
84+ case "desktop", "mac", "macos": desktopCountsAs
85+ case "apple vision", "vision", "apple vision pro", "visionos", "vision pro": "Vision Pro"
86+ case "apple tv", "appletv", "tvos": "Apple TV"
87+ case "apple watch", "watchos": "Apple Watch"
88+ default: device
89+ }
90+ }
91+
92+ static func parse(tsv: String, day: String, appIDs: Set<String>, desktop: [String: String] = [:]) -> [DataPoint] {
93+ let lines = tsv.split(whereSeparator: \.isNewline).map { $0.components(separatedBy: "\t") }
94+ guard let header = lines.first,
95+ let idCol = header.firstIndex(of: "Apple Identifier"), let unitsCol = header.firstIndex(of: "Units"),
96+ let typeCol = header.firstIndex(of: "Product Type Identifier"), let deviceCol = header.firstIndex(of: "Device")
97+ else { return [] }
98+ var totals: [String: Double] = [:] // "appID|metric|device"
99+ for row in lines.dropFirst() where row.count > max(idCol, unitsCol, typeCol, deviceCol) {
100+ let id = row[idCol], type = row[typeCol]
101+ guard appIDs.isEmpty || appIDs.contains(id) else { continue }
102+ let metric: Metric
103+ if downloadTypes.contains(type) { metric = .appDownloads }
104+ else if redownloadTypes.contains(type) { metric = .appRedownloads }
105+ else { continue }
106+ let device = Self.platform(device: row[deviceCol], desktopCountsAs: desktop[id] ?? "Mac")
107+ totals["\(id)|\(metric.rawValue)|\(device)", default: 0] += Double(row[unitsCol]) ?? 0
108+ }
109+ var appTotals: [String: Double] = [:] // "appID|metric": the day's total across devices
110+ let platformPoints = totals.map { key, value -> DataPoint in
111+ let p = key.components(separatedBy: "|")
112+ appTotals["\(p[0])|\(p[1])", default: 0] += value
113+ return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: "platform:" + p[2], value: value)
114+ }
115+ let totalPoints = appTotals.map { key, value -> DataPoint in
116+ let p = key.components(separatedBy: "|")
117+ return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: nil, value: value)
118+ }
119+ return totalPoints + platformPoints
120+ }
121+
122+ /// ES256 JWT, valid 20 minutes.
123+ func token(now: Date = .now, credentials: Credentials? = nil) throws -> String {
124+ guard let c = credentials ?? Credentials.saved else { throw AnalyticsError.notSignedIn("App Store Connect") }
125+ let kid = c.keyID, iss = c.issuerID, pem = c.privateKey
126+ let key = try P256.Signing.PrivateKey(pemRepresentation: pem)
127+ let header = try JSONSerialization.data(withJSONObject: ["alg": "ES256", "kid": kid, "typ": "JWT"])
128+ let iat = Int(now.timeIntervalSince1970)
129+ let payload = try JSONSerialization.data(withJSONObject: ["iss": iss, "iat": iat, "exp": iat + 1200, "aud": "appstoreconnect-v1"])
130+ let signingInput = header.base64URL + "." + payload.base64URL
131+ let signature = try key.signature(for: Data(signingInput.utf8))
132+ return signingInput + "." + signature.rawRepresentation.base64URL
133+ }
134+ }
135+
136+ /// Public star ratings and written reviews (no key): the iTunes lookup in every storefront and the customer
137+ /// reviews feed, for every app by the same developer (new apps are found automatically). Same as the old
138+ /// `reviews/pull_reviews.py`.
139+ public struct AppStoreRatings: Sendable {
140+ let session: URLSession
141+ public init(session: URLSession = .shared) { self.session = session }
142+
143+ public static let storefronts = ("ae ag ai al am ao ar at au az bb be bf bg bh bj bm bn bo br bs bt bw by bz ca cg ch cl cn co cr "
144+ + "cv cy cz de dk dm do dz ec ee eg es fi fj fm fr gb gd gh gm gr gt gw gy hk hn hr hu id ie il in "
145+ + "is it jm jo jp ke kg kh kn kr kw ky kz la lb lc lk lr lt lu lv md mg mk ml mn mo mr ms mt mu mw "
146+ + "mx my mz na ne ng ni nl no np nz om pa pe pg ph pk pl pt pw py qa ro ru sa sb sc se sg si sk sl "
147+ + "sn sr st sv sz tc td th tj tm tn tr tt tw tz ua ug us uy uz vc ve vg vn ye za zw").split(separator: " ").map(String.init)
148+
149+ public struct Result: Sendable {
150+ public var points: [DataPoint] = []
151+ public var reviews: [Review] = []
152+ /// Apple ID → newest App Store name, every app by the developer (including ones not tracked yet).
153+ public var names: [String: String] = [:]
154+ }
155+
156+ func get(_ url: URL) async -> [String: Any]? {
157+ for _ in 0..<3 {
158+ var r = URLRequest(url: url); r.timeoutInterval = 20
159+ r.setValue("Mozilla/5.0 (Macintosh) Graphley", forHTTPHeaderField: "User-Agent")
160+ if let json = try? await session.json(r) { return json }
161+ }
162+ return nil
163+ }
164+
165+ /// Apple ID → name for every app by the developer of `seed`.
166+ public func discover(seed: [String]) async throws -> [String: String] {
167+ guard let lookup = await get(URL(string: "https://itunes.apple.com/lookup?id=\(seed.joined(separator: ","))&country=us")!),
168+ let results = lookup["results"] as? [[String: Any]], !results.isEmpty
169+ else { throw AnalyticsError.badResponse("Apple's app lookup (ratings not updated this run)") }
170+ var apps: [String: String] = [:]
171+ var artists = Set<Int>()
172+ for r in results {
173+ if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) }
174+ if let a = r["artistId"] as? Int { artists.insert(a) }
175+ }
176+ for artist in artists {
177+ let url = URL(string: "https://itunes.apple.com/lookup?id=\(artist)&entity=software,macSoftware,iPadSoftware&country=us")!
178+ for r in (await get(url))?["results"] as? [[String: Any]] ?? [] where r["wrapperType"] as? String == "software" {
179+ if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) }
180+ }
181+ }
182+ return apps
183+ }
184+
185+ /// Today's weighted average and count per app (and count by country), plus written reviews from every
186+ /// storefront that has ratings and the US. Refuses the day when more than a tenth of the lookups fail.
187+ public func pull(seed: [String], today: String = DayKey.string(.now), firstSeen: [String: String] = [:]) async throws -> Result {
188+ var result = Result()
189+ result.names = try await discover(seed: seed)
190+ let ids = result.names.keys.sorted()
191+ struct Hit: Sendable { var country: String; var id: String; var avg: Double; var count: Int }
192+ struct Lookup: Sendable { var hits: [Hit]; var ok: Bool }
193+ var hits: [Hit] = []
194+ var failed = 0
195+ let joined = ids.joined(separator: ",")
196+ // Eight storefronts at a time.
197+ for start in stride(from: 0, to: Self.storefronts.count, by: 8) {
198+ let batch = Array(Self.storefronts[start..<min(start + 8, Self.storefronts.count)])
199+ let lookups = await withTaskGroup(of: Lookup.self, returning: [Lookup].self) { group in
200+ for country in batch {
201+ group.addTask {
202+ let url = URL(string: "https://itunes.apple.com/lookup?id=\(joined)&country=\(country)")!
203+ guard let rows = (await get(url))?["results"] as? [[String: Any]] else { return Lookup(hits: [], ok: false) }
204+ return Lookup(hits: rows.compactMap { r -> Hit? in
205+ guard let id = (r["trackId"] as? Int).map(String.init), let count = r["userRatingCount"] as? Int, count > 0 else { return nil }
206+ return Hit(country: country.uppercased(), id: id, avg: r["averageUserRating"] as? Double ?? 0, count: count)
207+ }, ok: true)
208+ }
209+ }
210+ var all: [Lookup] = []
211+ for await l in group { all.append(l) }
212+ return all
213+ }
214+ for l in lookups { if l.ok { hits += l.hits } else { failed += 1 } }
215+ }
216+ if failed > Self.storefronts.count / 10 {
217+ throw AnalyticsError.badResponse("\(failed) App Store storefront lookups failed, so ratings weren't recorded today")
218+ }
219+ for id in ids {
220+ let mine = hits.filter { $0.id == id }
221+ let count = mine.reduce(0) { $0 + $1.count }
222+ result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, value: Double(count)))
223+ if count > 0 {
224+ let avg = mine.reduce(0) { $0 + $1.avg * Double($1.count) } / Double(count)
225+ result.points.append(DataPoint(day: today, subject: id, metric: .rating, value: (avg * 100).rounded() / 100))
226+ }
227+ for h in mine { result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, breakdown: "country:" + h.country, value: Double(h.count))) }
228+ }
229+ // Written reviews: every storefront with ratings, plus the US (the feed can lead the count).
230+ let targets = Set(hits.map { "\($0.country.lowercased())|\($0.id)" } + ids.map { "us|\($0)" }).sorted()
231+ let names = result.names
232+ let fetched = await withTaskGroup(of: [Review].self, returning: [Review].self) { group in
233+ for t in targets {
234+ let p = t.components(separatedBy: "|")
235+ let name = names[p[1]] ?? p[1]
236+ group.addTask { await reviews(country: p[0], appID: p[1], appName: name, today: today) }
237+ }
238+ var all: [Review] = []
239+ for await list in group { all += list }
240+ return all
241+ }
242+ result.reviews += fetched
243+ for i in result.reviews.indices { result.reviews[i].firstSeen = firstSeen[result.reviews[i].id] ?? today }
244+ return result
245+ }
246+
247+ func reviews(country: String, appID: String, appName: String, today: String) async -> [Review] {
248+ func label(_ v: Any?) -> String {
249+ if let list = v as? [Any] { return label(list.first) }
250+ return (v as? [String: Any])?["label"] as? String ?? ""
251+ }
252+ var out: [Review] = []
253+ for page in 1...2 {
254+ let url = URL(string: "https://itunes.apple.com/\(country)/rss/customerreviews/page=\(page)/id=\(appID)/sortby=mostrecent/json")!
255+ let feed = (await get(url))?["feed"] as? [String: Any]
256+ var entries = feed?["entry"] as? [[String: Any]] ?? []
257+ if let single = feed?["entry"] as? [String: Any] { entries = [single] }
258+ entries = entries.filter { $0["im:rating"] != nil }
259+ for e in entries {
260+ out.append(Review(id: label(e["id"]), appID: appID, appName: appName, country: country.uppercased(),
261+ stars: Int(label(e["im:rating"])) ?? 0, title: label(e["title"]), text: label(e["content"]),
262+ version: label(e["im:version"]), author: label((e["author"] as? [String: Any])?["name"]),
263+ date: String(label(e["updated"]).prefix(10)), firstSeen: today,
264+ url: "https://apps.apple.com/\(country)/app/id\(appID)?see-all=reviews"))
265+ }
266+ if entries.count < 50 { break }
267+ }
268+ return out
269+ }
270+ }
271+
272+ extension Data {
273+ var base64URL: String {
274+ base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
275+ }
276+ }
277+
278+ enum Gzip {
279+ /// Strips the gzip header and trailer, then inflates the raw DEFLATE stream.
280+ static func inflate(_ data: Data) throws -> Data {
281+ let b = [UInt8](data)
282+ guard b.count > 18, b[0] == 0x1f, b[1] == 0x8b, b[2] == 8 else { return data } // not gzip: return as is
283+ let flags = b[3]; var i = 10
284+ if flags & 0x04 != 0 { i += 2 + Int(b[i]) + Int(b[i + 1]) << 8 } // FEXTRA
285+ if flags & 0x08 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FNAME
286+ if flags & 0x10 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FCOMMENT
287+ if flags & 0x02 != 0 { i += 2 } // FHCRC
288+ let deflate = Data(b[i..<(b.count - 8)])
289+ return try (deflate as NSData).decompressed(using: .zlib) as Data
290+ }
291+ }

Sources/AnalyticsKit/Credentials.swift added

1+ import Foundation
2+
3+ /// Helpers the apps use to show and save Google keys without seeing the key material.
4+ public enum GoogleServiceAccountKey {
5+ /// The service account's email (client_email) if a key is saved.
6+ public static var savedEmail: String? {
7+ Keychain.get(.googleServiceAccount).flatMap { try? ServiceAccount(json: $0).clientEmail }
8+ }
9+ /// Validates the JSON key file and saves it. Returns the service account's email.
10+ @discardableResult
11+ public static func save(json: String) throws -> String {
12+ let account = try ServiceAccount(json: json)
13+ try Keychain.set(json, for: .googleServiceAccount)
14+ return account.clientEmail
15+ }
16+ public static func remove() { Keychain.remove(.googleServiceAccount) }
17+ }

Sources/AnalyticsKit/GA4Reports.swift added

1+ import Foundation
2+
3+ /// Everything Graphley pulls from GA4 for one site, the same reports as the old `ga4_pull.py`:
4+ /// daily traffic, 30-day summaries, top pages, channels, top sources, visits from AI assistants, every
5+ /// tracked event per day, detail breakdowns (clicks by section and destination, scroll, sections seen,
6+ /// forms, video, files, builder steps, CTAs) and the paid landing-page funnel.
7+ public struct GA4SiteView: Sendable {
8+ public struct Section: Sendable, Hashable {
9+ public var prefix: String; public var host: String?; public var contentGroup: String? = nil
10+ }
11+ public enum Scope: Sendable, Hashable {
12+ case whole
13+ /// A site that has sections reported on their own: everything except them (old pull's main view).
14+ case excluding([Section])
15+ /// A section of a site: page path prefix OR its old host name OR its content group.
16+ case only(Section)
17+ }
18+ public var site: Site
19+ public var property: String
20+ public var scope: Scope
21+ public var isSection: Bool { if case .only = scope { true } else { false } }
22+
23+ /// One view per tracked site, with the parent's sections taken out of the parent.
24+ public static func views(for sites: [Site]) -> [GA4SiteView] {
25+ let live = sites.filter { !$0.archived }
26+ return live.compactMap { site in
27+ if let parentID = site.parentID {
28+ guard let parent = live.first(where: { $0.id == parentID }) ?? sites.first(where: { $0.id == parentID }),
29+ let property = site.ga4PropertyID ?? parent.ga4PropertyID, let prefix = site.pathPrefix else { return nil }
30+ return GA4SiteView(site: site, property: property, scope: .only(Section(prefix: prefix, host: site.legacyHost, contentGroup: site.contentGroup)))
31+ }
32+ guard let property = site.ga4PropertyID else { return nil }
33+ let sections = live.filter { $0.parentID == site.id }.compactMap { s in s.pathPrefix.map { Section(prefix: $0, host: s.legacyHost, contentGroup: s.contentGroup) } }
34+ return GA4SiteView(site: site, property: property, scope: sections.isEmpty ? .whole : .excluding(sections))
35+ }
36+ }
37+
38+ var filter: [String: Any]? {
39+ func expr(_ s: Section) -> [String: Any] {
40+ var parts: [[String: Any]] = [["filter": ["fieldName": "pagePath", "stringFilter": ["matchType": "BEGINS_WITH", "value": s.prefix]]]]
41+ if let host = s.host { parts.append(["filter": ["fieldName": "hostName", "stringFilter": ["matchType": "EXACT", "value": host]]]) }
42+ if let group = s.contentGroup { parts.append(["filter": ["fieldName": "contentGroup", "stringFilter": ["matchType": "EXACT", "value": group]]]) }
43+ return ["orGroup": ["expressions": parts]]
44+ }
45+ switch scope {
46+ case .whole: return nil
47+ case .only(let s): return expr(s)
48+ case .excluding(let list): return ["notExpression": ["orGroup": ["expressions": list.map(expr)]]]
49+ }
50+ }
51+ }
52+
53+ public extension GoogleAnalytics {
54+ /// Every event the sites send that Graphley counts per day (downloads, buttons and detail tracking).
55+ static let trackedEvents = [
56+ "mac_installer_download", "download_click_mac", "app_store_click", "download_click_ios", "source_click", "source_download",
57+ "newsletter_click", "bug_report_click", "film_play_sound", "tutorial_play", "sign_in_click", "save_tutorial", "unsave_tutorial",
58+ "roadmap_create", "roadmap_recalibrate", "book_call", "generate_lead", "resume_open", "resume_download", "email_click",
59+ "outbound_click", "nav_click", "internal_click", "cta_click", "button_click", "product_site_click", "phone_click",
60+ "file_download_click", "section_click", "text_copy", "scroll_depth", "section_view", "engaged_time", "form_started",
61+ "form_submitted", "form_abandon", "form_start", "video_play", "video_start", "video_progress", "video_complete",
62+ "askp_message", "builder_step", "begin_checkout", "app_feedback", "petition_signed", "petition_resigned",
63+ "congress_message_copied"
64+ ]
65+ static let clickEvents = ["nav_click", "internal_click", "outbound_click", "app_store_click", "product_site_click", "email_click",
66+ "phone_click", "file_download_click", "button_click", "section_click", "cta_click", "newsletter_click",
67+ "resume_open", "resume_download", "source_click", "download_click_mac", "download_click_ios", "mac_installer_download"]
68+
69+ /// AI assistants by source text (the old pull's AI_ASSISTANTS), first match wins.
70+ static let aiAssistants: [(pattern: String, name: String)] = [
71+ ("chatgpt|openai", "ChatGPT"), ("perplexity", "Perplexity"), ("claude|anthropic", "Claude"),
72+ ("gemini\\.google|bard\\.google", "Gemini"), ("copilot", "Copilot"), ("(^|\\.)grok\\.com|^x\\.ai$", "Grok"),
73+ ("(^|\\.)meta\\.ai", "Meta AI"), ("deepseek", "DeepSeek"), ("mistral\\.ai", "Mistral"), ("(^|\\.)you\\.com", "You.com"),
74+ ("phind", "Phind"), ("(^|\\.)poe\\.com", "Poe"), ("duck\\.ai", "Duck.ai"), ("kagi\\.com", "Kagi")
75+ ]
76+ static func aiAssistant(_ source: String) -> String {
77+ aiAssistants.first { source.range(of: $0.pattern, options: [.regularExpression, .caseInsensitive]) != nil }?.name ?? "Other AI"
78+ }
79+
80+ static let paidSources = ["google / cpc": "google / cpc", "linkedin / paid-social": "linkedin / paid-social", "linkedin / paid_social": "linkedin / paid-social"]
81+ static let funnelEvents = ["book_call", "generate_lead", "form_start", "scroll", "resume_download", "file_download", "outbound_click"]
82+
83+ /// All reports for one site. `days` of daily history (180 so a 90-day range can compare with the 90 before).
84+ func pull(_ view: GA4SiteView, days: Int = 180) async throws -> [DataPoint] {
85+ let subject = view.site.id
86+ let yesterday = DayKey.lastDays(1).last ?? DayKey.string(.now)
87+ var out: [DataPoint] = []
88+
89+ // Daily traffic.
90+ let metrics: [Metric] = [.users, .newUsers, .sessions, .pageViews, .engagedSessions]
91+ for row in try await rows(view, ["date"], metrics.compactMap(\.ga4Name), start: "\(days)daysAgo") {
92+ for (m, v) in zip(metrics, row.values) { out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: m, value: v)) }
93+ }
94+
95+ // Unique visitors over the last 30 days and the 30 before (what the old summary compared).
96+ let summary = try await runReport(property: view.property, body: body(view, [], ["activeUsers", "newUsers", "sessions", "screenPageViews"],
97+ ranges: [["startDate": "30daysAgo", "endDate": "yesterday", "name": "last_30"], ["startDate": "60daysAgo", "endDate": "31daysAgo", "name": "prev_30"]]))
98+ for row in Self.table(summary) {
99+ let period = row.dims.last ?? ""
100+ for (m, v) in zip([Metric.users, .newUsers, .sessions, .pageViews], row.values) {
101+ out.append(DataPoint(day: yesterday, subject: subject, metric: m, breakdown: "period:" + period, value: v))
102+ }
103+ }
104+
105+ // Top pages, with paths that moved shown under their new path.
106+ var pages: [String: Double] = [:]
107+ for row in try await rows(view, ["pagePath"], ["screenPageViews"], start: "30daysAgo", order: "screenPageViews", limit: view.site.pageLimit ?? 10) {
108+ let path = view.site.pathAliases?[row.dims[0]] ?? row.dims[0]
109+ pages[path, default: 0] += row.values[0]
110+ }
111+ out += pages.map { DataPoint(day: yesterday, subject: subject, metric: .pageViews, breakdown: "page:" + $0.key, value: $0.value) }
112+
113+ for row in try await rows(view, ["sessionDefaultChannelGroup"], ["sessions"], start: "30daysAgo", order: "sessions") {
114+ out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "channel:" + row.dims[0], value: row.values[0]))
115+ }
116+ for row in try await rows(view, ["sessionSourceMedium"], ["sessions"], start: "30daysAgo", order: "sessions", limit: 10) {
117+ out.append(DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "source:" + row.dims[0], value: row.values[0]))
118+ }
119+
120+ // Visits from AI assistants: GA4's AI Assistant channel plus sources GA4 hasn't classified yet.
121+ let aiFilter: [String: Any] = ["orGroup": ["expressions": [
122+ ["filter": ["fieldName": "sessionDefaultChannelGroup", "stringFilter": ["matchType": "EXACT", "value": "AI Assistant"]]],
123+ ["filter": ["fieldName": "sessionSource", "stringFilter": ["matchType": "PARTIAL_REGEXP", "value": Self.aiAssistants.map(\.pattern).joined(separator: "|"), "caseSensitive": false]]]
124+ ]]]
125+ var ai: [String: Double] = [:], aiLanding: [String: Double] = [:]
126+ for row in try await rows(view, ["date", "sessionSource", "landingPage"], ["sessions"], start: "90daysAgo", filter: aiFilter) {
127+ let name = Self.aiAssistant(row.dims[1])
128+ ai["\(Self.dayKey(row.dims[0]))|\(name)", default: 0] += row.values[0]
129+ let landing = row.dims[2].components(separatedBy: "?").first.flatMap { $0.isEmpty ? "/" : $0 } ?? "/"
130+ if Self.dayKey(row.dims[0]) >= (DayKey.lastDays(30).first ?? "") { aiLanding["\(name) → \(landing)", default: 0] += row.values[0] }
131+ }
132+ out += ai.map { key, v in
133+ let p = key.components(separatedBy: "|")
134+ return DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: "ai:" + p[1], value: v)
135+ }
136+ out += aiLanding.map { DataPoint(day: yesterday, subject: subject, metric: .sessions, breakdown: "ailanding:" + $0.key, value: $0.value) }
137+
138+ // Every tracked event, per day.
139+ let eventFilter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.trackedEvents]]]
140+ for row in try await rows(view, ["date", "eventName"], ["eventCount"], start: "\(days)daysAgo", filter: eventFilter) {
141+ out.append(DataPoint(day: Self.dayKey(row.dims[0]), subject: subject, metric: .keyEvent, event: row.dims[1], value: row.values[0]))
142+ }
143+
144+ if !view.isSection { out += try await detail(view, day: yesterday) }
145+ if let landings = view.site.funnelLandings, !landings.isEmpty { out += try await funnel(view, landings: landings) }
146+ return out
147+ }
148+
149+ /// 30-day detail breakdowns. Custom dimensions are used only once registered on the property.
150+ func detail(_ view: GA4SiteView, day: String) async throws -> [DataPoint] {
151+ let have = try await dimensions(property: view.property)
152+ func first(_ names: String...) -> String? { names.first(where: have.contains) }
153+ func list(_ events: [String]) -> [String: Any] { ["filter": ["fieldName": "eventName", "inListFilter": ["values": events]]] }
154+ let subject = view.site.id
155+ var totals: [String: Double] = [:] // "event|family:value"
156+ func add(_ dim: String?, family: String, events: [String], clean: (String) -> String = { $0 }) async throws {
157+ guard let dim else { return }
158+ // Per property, like the old pull: detail isn't split by section.
159+ for row in try await rows(view, ["eventName", dim], ["eventCount"], start: "30daysAgo", limit: 2_000, filter: list(events), sectionFilter: false) {
160+ let value = row.dims[1]
161+ guard !value.isEmpty, value != "(not set)" else { continue }
162+ totals["\(row.dims[0])|\(family):\(clean(value))", default: 0] += row.values[0]
163+ }
164+ }
165+ let clicks = Self.clickEvents
166+ try await add(first("customEvent:link_section", "contentId"), family: "section", events: clicks + ["section_view"].filter { _ in first("customEvent:section_id") == nil })
167+ if let sectionID = first("customEvent:section_id") { try await add(sectionID, family: "section", events: ["section_view"]) }
168+ try await add("linkDomain", family: "domain", events: clicks) { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 }
169+ try await add(first("customEvent:percent_scrolled", "percentScrolled"), family: "scroll", events: ["scroll_depth", "scroll"])
170+ try await add(first("customEvent:form_id"), family: "form", events: ["form_started", "form_submitted", "form_abandon", "form_start"])
171+ try await add(first("customEvent:last_field"), family: "field", events: ["form_abandon"])
172+ try await add("videoTitle", family: "video", events: ["video_play", "video_start", "video_progress", "video_complete"])
173+ try await add("fileName", family: "file", events: ["resume_download", "file_download_click", "mac_installer_download", "source_download"])
174+ try await add("contentId", family: "step", events: ["builder_step", "begin_checkout"])
175+ try await add(first("customEvent:cta"), family: "cta", events: ["cta_click"])
176+ return totals.map { key, v in
177+ let p = key.split(separator: "|", maxSplits: 1).map(String.init)
178+ return DataPoint(day: day, subject: subject, metric: .keyEvent, breakdown: p[1], event: p[0], value: v)
179+ }
180+ }
181+
182+ /// Paid-ad funnel per day per landing page per paid source: sessions, engaged sessions, funnel events and CTA
183+ /// clicks split by their `cta` parameter (`book_call_open`, `lp_write_instead`). Ads are off, the funnel stays.
184+ func funnel(_ view: GA4SiteView, landings: [String]) async throws -> [DataPoint] {
185+ let subject = view.site.id
186+ func key(_ dims: [String]) -> String? {
187+ let source = Self.paidSources[dims[2]] ?? "other"
188+ guard source != "other" || landings.contains(dims[1]) else { return nil }
189+ return "\(Self.dayKey(dims[0]))|funnel:\(dims[1])|\(source)"
190+ }
191+ var out: [DataPoint] = []
192+ var sums: [String: [Double]] = [:]
193+ for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium"], ["sessions", "engagedSessions"], start: "90daysAgo", sectionFilter: false) {
194+ guard let k = key(row.dims) else { continue }
195+ sums[k] = zip(sums[k] ?? [0, 0], row.values).map(+)
196+ }
197+ for (k, v) in sums {
198+ let p = k.components(separatedBy: "|"), b = p[1] + "|" + p[2]
199+ out.append(DataPoint(day: p[0], subject: subject, metric: .sessions, breakdown: b, value: v[0]))
200+ out.append(DataPoint(day: p[0], subject: subject, metric: .engagedSessions, breakdown: b, value: v[1]))
201+ }
202+ var events: [String: Double] = [:]
203+ let filter: [String: Any] = ["filter": ["fieldName": "eventName", "inListFilter": ["values": Self.funnelEvents]]]
204+ for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "eventName"], ["eventCount"], start: "90daysAgo", filter: filter, sectionFilter: false) {
205+ guard let k = key(row.dims) else { continue }
206+ events[k + "|" + row.dims[3], default: 0] += row.values[0]
207+ }
208+ if try await dimensions(property: view.property).contains("customEvent:cta") {
209+ let cta: [String: Any] = ["filter": ["fieldName": "eventName", "stringFilter": ["value": "cta_click"]]]
210+ for row in try await rows(view, ["date", "landingPage", "sessionSourceMedium", "customEvent:cta"], ["eventCount"], start: "90daysAgo", filter: cta, sectionFilter: false) {
211+ guard let k = key(row.dims) else { continue }
212+ let name = ["book_call_open", "lp_write_instead"].contains(row.dims[3]) ? row.dims[3] : "other_cta"
213+ events[k + "|cta:" + name, default: 0] += row.values[0]
214+ }
215+ }
216+ for (k, v) in events {
217+ let p = k.components(separatedBy: "|")
218+ out.append(DataPoint(day: p[0], subject: subject, metric: .keyEvent, breakdown: p[1] + "|" + p[2], event: p[3], value: v))
219+ }
220+ return out
221+ }
222+
223+ // MARK: Plumbing
224+
225+ struct Row { var dims: [String]; var values: [Double] }
226+
227+ func rows(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], start: String, order: String? = nil, limit: Int? = nil,
228+ filter: [String: Any]? = nil, sectionFilter: Bool = true) async throws -> [Row] {
229+ var b = body(view, dims, metrics, ranges: [["startDate": start, "endDate": "yesterday"]], filter: filter, sectionFilter: sectionFilter)
230+ if let order { b["orderBys"] = [["metric": ["metricName": order], "desc": true]] }
231+ b["limit"] = limit ?? 25_000
232+ return Self.table(try await runReport(property: view.property, body: b))
233+ }
234+
235+ func body(_ view: GA4SiteView, _ dims: [String], _ metrics: [String], ranges: [[String: String]], filter: [String: Any]? = nil,
236+ sectionFilter: Bool = true) -> [String: Any] {
237+ var b: [String: Any] = ["dateRanges": ranges, "dimensions": dims.map { ["name": $0] }, "metrics": metrics.map { ["name": $0] }]
238+ let parts = [filter, sectionFilter ? view.filter : nil].compactMap { $0 }
239+ if parts.count == 1 { b["dimensionFilter"] = parts[0] }
240+ else if parts.count == 2 { b["dimensionFilter"] = ["andGroup": ["expressions": parts]] }
241+ return b
242+ }
243+
244+ static func table(_ json: [String: Any]) -> [Row] {
245+ (json["rows"] as? [[String: Any]] ?? []).map { Row(dims: dims($0), values: mets($0)) }
246+ }
247+
248+ /// API names of the dimensions a property can report (custom dimensions appear once registered).
249+ func dimensions(property: String) async throws -> Set<String> {
250+ let token = try await auth.accessToken()
251+ var r = URLRequest(url: URL(string: "https://analyticsdata.googleapis.com/v1beta/properties/\(property)/metadata")!)
252+ r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
253+ let json = try await session.json(r, retries: 3)
254+ return Set((json["dimensions"] as? [[String: Any]] ?? []).compactMap { $0["apiName"] as? String })
255+ }
256+
257+ /// Web stream measurement IDs and URLs of a property ("G-DRL62HKS7W"), to match sites the way the old pull did.
258+ func streams(property: String) async throws -> [(measurementID: String, url: String)] {
259+ let token = try await auth.accessToken()
260+ var r = URLRequest(url: URL(string: "https://analyticsadmin.googleapis.com/v1beta/properties/\(property)/dataStreams")!)
261+ r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
262+ let json = try await session.json(r, retries: 2)
263+ return (json["dataStreams"] as? [[String: Any]] ?? []).compactMap { s in
264+ guard let web = s["webStreamData"] as? [String: Any], let id = web["measurementId"] as? String else { return nil }
265+ return (id, web["defaultUri"] as? String ?? "")
266+ }
267+ }
268+ }

Sources/AnalyticsKit/GoogleAnalytics.swift added

1+ import Foundation
2+
3+ /// Google sign-in for an installed app: the Mac app runs the loopback + PKCE flow once (see
4+ /// `GoogleSignIn` in the Mac target) and saves the refresh token in the Keychain. A saved service
5+ /// account key (see `ServiceAccount`) is used instead when present. Scope: analytics.readonly.
6+ public struct GoogleAuth: Sendable {
7+ public static let scope = "https://www.googleapis.com/auth/analytics.readonly"
8+ /// A service account also reads Search Console (add it as a Restricted user on each property).
9+ public static let serviceAccountScope = scope + " https://www.googleapis.com/auth/webmasters.readonly"
10+ /// Desktop-type OAuth client shipped with the app. Users can supply their own in Settings.
11+ public static let defaultClientID = "REPLACE_WITH_DESKTOP_CLIENT_ID.apps.googleusercontent.com"
12+ let session: URLSession
13+
14+ public init(session: URLSession = .shared) { self.session = session }
15+
16+ /// Signed in with Google, or a service account key is saved.
17+ public static var isConfigured: Bool { Keychain.has(.googleServiceAccount) || Keychain.has(.googleRefreshToken) }
18+
19+ /// Uses the saved service account key when there is one, otherwise the sign-in refresh token.
20+ public func accessToken() async throws -> String {
21+ if let json = Keychain.get(.googleServiceAccount) {
22+ return try await exchange(["grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
23+ "assertion": try ServiceAccount(json: json).assertion()])
24+ }
25+ guard let refresh = Keychain.get(.googleRefreshToken) else { throw AnalyticsError.notSignedIn("Google") }
26+ let clientID = Keychain.get(.googleClientID) ?? Self.defaultClientID
27+ return try await exchange(["client_id": clientID, "grant_type": "refresh_token", "refresh_token": refresh])
28+ }
29+
30+ private func exchange(_ fields: [String: String]) async throws -> String {
31+ var request = URLRequest(url: URL(string: "https://oauth2.googleapis.com/token")!)
32+ request.httpMethod = "POST"
33+ request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
34+ request.httpBody = form(fields)
35+ let json = try await session.json(request)
36+ guard let token = json["access_token"] as? String else { throw AnalyticsError.badResponse("Google token") }
37+ return token
38+ }
39+
40+ private func form(_ fields: [String: String]) -> Data {
41+ var c = URLComponents(); c.queryItems = fields.map { URLQueryItem(name: $0, value: $1) }
42+ return Data((c.percentEncodedQuery ?? "").utf8)
43+ }
44+ }
45+
46+ /// GA4 Admin API (find properties) and Data API (daily reports).
47+ public struct GoogleAnalytics: Sendable {
48+ public struct Property: Sendable, Hashable, Codable {
49+ public let id: String // "564127557"
50+ public let name: String // "Textley"
51+ public let account: String // "Protomota"
52+ }
53+
54+ let auth: GoogleAuth
55+ let session: URLSession
56+ public init(auth: GoogleAuth = .init(), session: URLSession = .shared) { self.auth = auth; self.session = session }
57+
58+ /// Every GA4 property the signed-in Google account can read. Agents call this through
59+ /// `discover_ga4_properties` and then `add_site` for the ones the user wants.
60+ public func properties() async throws -> [Property] {
61+ let token = try await auth.accessToken()
62+ var found: [Property] = []
63+ var pageToken: String?
64+ repeat {
65+ var c = URLComponents(string: "https://analyticsadmin.googleapis.com/v1beta/accountSummaries")!
66+ c.queryItems = [URLQueryItem(name: "pageSize", value: "200")] + (pageToken.map { [URLQueryItem(name: "pageToken", value: $0)] } ?? [])
67+ var r = URLRequest(url: c.url!); r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
68+ let json = try await session.json(r)
69+ found += Self.parseAccountSummaries(json)
70+ pageToken = json["nextPageToken"] as? String
71+ } while pageToken?.isEmpty == false
72+ return found
73+ }
74+
75+ static func parseAccountSummaries(_ json: [String: Any]) -> [Property] {
76+ let accounts = json["accountSummaries"] as? [[String: Any]] ?? []
77+ return accounts.flatMap { account -> [Property] in
78+ let accountName = account["displayName"] as? String ?? ""
79+ return (account["propertySummaries"] as? [[String: Any]] ?? []).compactMap { p in
80+ guard let ref = p["property"] as? String else { return nil }
81+ return Property(id: ref.replacingOccurrences(of: "properties/", with: ""),
82+ name: p["displayName"] as? String ?? ref, account: accountName)
83+ }
84+ }
85+ }
86+
87+ /// Daily users, new users, sessions and page views for one site.
88+ public func daily(site: Site, days: Int = 90) async throws -> [DataPoint] {
89+ guard let property = site.ga4PropertyID else { return [] }
90+ let metrics: [Metric] = [.users, .newUsers, .sessions, .pageViews, .engagedSessions]
91+ let body: [String: Any] = [
92+ "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
93+ "dimensions": [["name": "date"]],
94+ "metrics": metrics.compactMap(\.ga4Name).map { ["name": $0] },
95+ "keepEmptyRows": true
96+ ]
97+ let json = try await runReport(property: property, body: body)
98+ return Self.parseDaily(json, subject: site.id, metrics: metrics)
99+ }
100+
101+ /// Top page paths over the last `days` days, stored on the last day with `breakdown` = path.
102+ public func topPages(site: Site, days: Int = 30, limit: Int = 10) async throws -> [DataPoint] {
103+ guard let property = site.ga4PropertyID else { return [] }
104+ let body: [String: Any] = [
105+ "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
106+ "dimensions": [["name": "pagePath"]],
107+ "metrics": [["name": "screenPageViews"]],
108+ "orderBys": [["metric": ["metricName": "screenPageViews"], "desc": true]],
109+ "limit": limit
110+ ]
111+ let json = try await runReport(property: property, body: body)
112+ let day = DayKey.lastDays(1).last ?? DayKey.string(.now)
113+ return (json["rows"] as? [[String: Any]] ?? []).compactMap { row in
114+ guard let path = Self.dims(row).first, let v = Self.mets(row).first else { return nil }
115+ return DataPoint(day: day, subject: site.id, metric: .pageViews, breakdown: "page:" + path, value: v)
116+ }
117+ }
118+
119+ /// Daily counts of named key events (e.g. mac_installer_download, app_store_click).
120+ public func events(site: Site, names: [String], days: Int = 90) async throws -> [DataPoint] {
121+ guard let property = site.ga4PropertyID, !names.isEmpty else { return [] }
122+ let body: [String: Any] = [
123+ "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
124+ "dimensions": [["name": "date"], ["name": "eventName"]],
125+ "metrics": [["name": "eventCount"]],
126+ "dimensionFilter": ["filter": ["fieldName": "eventName", "inListFilter": ["values": names]]]
127+ ]
128+ let json = try await runReport(property: property, body: body)
129+ return (json["rows"] as? [[String: Any]] ?? []).compactMap { row in
130+ let d = Self.dims(row)
131+ guard d.count == 2, let v = Self.mets(row).first else { return nil }
132+ return DataPoint(day: Self.dayKey(d[0]), subject: site.id, metric: .keyEvent, event: d[1], value: v)
133+ }
134+ }
135+
136+ func runReport(property: String, body: [String: Any]) async throws -> [String: Any] {
137+ let token = try await auth.accessToken()
138+ var r = URLRequest(url: URL(string: "https://analyticsdata.googleapis.com/v1beta/properties/\(property):runReport")!)
139+ r.httpMethod = "POST"
140+ r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
141+ r.setValue("application/json", forHTTPHeaderField: "Content-Type")
142+ r.httpBody = try JSONSerialization.data(withJSONObject: body)
143+ return try await session.json(r, retries: 4)
144+ }
145+
146+ static func parseDaily(_ json: [String: Any], subject: String, metrics: [Metric]) -> [DataPoint] {
147+ (json["rows"] as? [[String: Any]] ?? []).flatMap { row -> [DataPoint] in
148+ guard let date = dims(row).first else { return [] }
149+ let values = mets(row)
150+ return zip(metrics, values).map { DataPoint(day: dayKey(date), subject: subject, metric: $0, value: $1) }
151+ }
152+ }
153+
154+ static func dims(_ row: [String: Any]) -> [String] { (row["dimensionValues"] as? [[String: Any]] ?? []).map { $0["value"] as? String ?? "" } }
155+ static func mets(_ row: [String: Any]) -> [Double] { (row["metricValues"] as? [[String: Any]] ?? []).map { Double($0["value"] as? String ?? "") ?? 0 } }
156+ /// GA4 returns dates as YYYYMMDD.
157+ static func dayKey(_ s: String) -> String {
158+ guard s.count == 8 else { return s }
159+ let a = Array(s); return "\(String(a[0..<4]))-\(String(a[4..<6]))-\(String(a[6..<8]))"
160+ }
161+ }
162+
163+ public enum AnalyticsError: Error, LocalizedError {
164+ case notSignedIn(String), badResponse(String), http(Int, String), missing(String), notAllowed(String)
165+ public var errorDescription: String? {
166+ switch self {
167+ case .notSignedIn(let s): "Sign in to \(s) in Sources & keys."
168+ case .badResponse(let s): "\(s) sent a response the app couldn't read."
169+ case .http(let code, let body): "Request failed (\(code)): \(body.prefix(200))"
170+ case .missing(let s): s
171+ case .notAllowed(let s): s
172+ }
173+ }
174+ }
175+
176+ extension URLSession {
177+ /// JSON request with retries on 429/5xx and timeouts (the old pull script needed the same).
178+ func json(_ request: URLRequest, retries: Int = 0) async throws -> [String: Any] {
179+ var attempt = 0
180+ while true {
181+ do {
182+ let (data, response) = try await data(for: request)
183+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
184+ if (code == 429 || code >= 500), attempt < retries {
185+ attempt += 1; try await Task.sleep(nanoseconds: UInt64(pow(2, Double(attempt))) * 1_000_000_000); continue
186+ }
187+ guard (200..<300).contains(code) else { throw AnalyticsError.http(code, String(decoding: data, as: UTF8.self)) }
188+ return (try JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
189+ } catch let e as URLError where e.code == .timedOut && attempt < retries {
190+ attempt += 1
191+ }
192+ }
193+ }
194+ }

97 more files changed.

Browse files at this commit