Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / AnalyticsView.swift
| 1 | import Charts |
| 2 | import SwiftUI |
| 3 | |
| 4 | struct AnalyticsView: View { |
| 5 | @Environment(\.studioPalette) private var palette |
| 6 | let workspace: Workspace |
| 7 | let openConnections: () -> Void |
| 8 | @State private var platform: SocialPlatform = .x |
| 9 | @State private var accountSelection = "" |
| 10 | @State private var interval = 30 |
| 11 | @State private var sort: AnalyticsReport.Metric = .engagement |
| 12 | @State private var warnings: [String] = [] |
| 13 | |
| 14 | private var analytics: AccountAnalytics { AccountAnalytics(workspace: workspace) } |
| 15 | private var accounts: [SocialPlatform: ManagedSocialAccount] { |
| 16 | var accounts: [SocialPlatform: ManagedSocialAccount] = [:] |
| 17 | for platform in SocialPlatform.allCases { accounts[platform] = analytics.account(platform) } |
| 18 | return accounts |
| 19 | } |
| 20 | |
| 21 | private var savedAccountIDs: [String] { |
| 22 | Set(workspace.records.filter { |
| 23 | ($0.kind.hasPrefix("analytics-") || $0.kind == "publication") && $0["platform"] == platform.rawValue |
| 24 | }.map { $0["accountId"] }.filter { !$0.isEmpty }).sorted() |
| 25 | } |
| 26 | |
| 27 | var body: some View { |
| 28 | let connected = accounts |
| 29 | let current = connected[platform] |
| 30 | let ids = ([current?.id].compactMap { $0 } + savedAccountIDs.filter { $0 != current?.id }) |
| 31 | let accountID = ids.contains(accountSelection) ? accountSelection : ids.first |
| 32 | let refreshAccount = current.flatMap { $0.id == accountID ? $0 : nil } |
| 33 | let state = accountID.flatMap { analytics.state(platform, accountID: $0) } |
| 34 | let capabilities = refreshAccount.map { analytics.capabilities(platform, account: $0) } |
| 35 | let canRefresh = capabilities.map { $0.followers || $0.posts } ?? false |
| 36 | let busy = workspace.refreshingAnalytics.contains(platform) |
| 37 | let report = AnalyticsReport(records: workspace.records, platform: platform, accountID: accountID, |
| 38 | days: interval, sort: sort) |
| 39 | StudioScrollView { |
| 40 | VStack(alignment: .leading, spacing: 18) { |
| 41 | HStack { |
| 42 | PageHeading(title: "Watch your work grow.", |
| 43 | subtitle: "Track your audience and see how published posts perform.") |
| 44 | Spacer() |
| 45 | if busy { ProgressView().controlSize(.small) } |
| 46 | Button("Refresh", systemImage: "arrow.clockwise") { Task { await refresh() } } |
| 47 | .disabled(busy || !canRefresh) |
| 48 | } |
| 49 | HStack(spacing: 18) { |
| 50 | Label("\(connected.count) connected accounts", systemImage: "person.2") |
| 51 | Label("\(AnalyticsReport.allConfirmed(workspace.records)) confirmed posts", systemImage: "checkmark.circle") |
| 52 | } |
| 53 | .font(.callout).foregroundStyle(.secondary) |
| 54 | HStack(alignment: .center, spacing: 12) { |
| 55 | StudioTabs(selection: $platform, tabs: SocialPlatform.allCases, label: { $0.name }, platform: { $0.rawValue }) |
| 56 | Spacer() |
| 57 | StudioChoicePicker(title: "Show", selection: $interval, options: [7, 30, 90, 0], |
| 58 | label: { $0 == 0 ? "All time" : "\($0) days" }) |
| 59 | } |
| 60 | if let accountID { |
| 61 | if ids.count > 1 { |
| 62 | StudioChoicePicker(title: "Account", |
| 63 | selection: Binding(get: { accountID }, set: { accountSelection = $0 }), |
| 64 | options: ids, label: { accountName($0, connected: current, distinguish: true) }) |
| 65 | } else { |
| 66 | Text(accountName(accountID, connected: current, distinguish: false)).font(.headline) |
| 67 | } |
| 68 | } |
| 69 | if refreshAccount != nil { |
| 70 | Toggle("Save a daily snapshot while Inkspring is open", isOn: Binding(get: { |
| 71 | analytics.automatic(platform) |
| 72 | }, set: { enabled in |
| 73 | workspace.perform { try analytics.setAutomatic(enabled, platform: platform) } |
| 74 | })) |
| 75 | .disabled(!canRefresh || busy) |
| 76 | } |
| 77 | if !canRefresh { |
| 78 | HStack { |
| 79 | Text(refreshAccount == nil ? "Connect \(platform.name) to refresh analytics." : |
| 80 | "This connection needs analytics read permission to refresh.") |
| 81 | .foregroundStyle(.secondary) |
| 82 | Button("Open Connections", action: openConnections) |
| 83 | } |
| 84 | } |
| 85 | ForEach(refreshWarnings(state), id: \.self) { Text($0).foregroundStyle(.secondary) } |
| 86 | overview(report, state: state) |
| 87 | if !report.posts.isEmpty { |
| 88 | VStack(alignment: .leading, spacing: 4) { |
| 89 | Text("The date range filters publication dates. Engagement totals use each post’s lifetime counts at its last refresh.") |
| 90 | if let count = report.latestFollowers?.accountPosts { |
| 91 | Text("The platform reports \(count.formatted()) \(platform == .tiktok ? "public videos" : "posts") on this profile.") |
| 92 | } |
| 93 | } |
| 94 | .font(.caption).foregroundStyle(.secondary) |
| 95 | } |
| 96 | followerChart(report) |
| 97 | activityChart(report) |
| 98 | rankedPosts(report) |
| 99 | if refreshAccount != nil, capabilities?.posts == true, let state, !state["cursor"].isEmpty { |
| 100 | Button("Load older posts") { Task { await refresh(older: true) } }.disabled(busy) |
| 101 | } |
| 102 | } |
| 103 | .studioPage() |
| 104 | } |
| 105 | .onChange(of: platform) { _, value in |
| 106 | accountSelection = "" |
| 107 | warnings = [] |
| 108 | sort = value == .reddit ? .score : .engagement |
| 109 | } |
| 110 | .onChange(of: accountSelection) { _, _ in warnings = [] } |
| 111 | } |
| 112 | |
| 113 | private func refreshWarnings(_ state: WorkspaceRecord?) -> [String] { |
| 114 | let saved = [state?["profileError"], state?["postsError"]].compactMap { $0 }.filter { !$0.isEmpty } |
| 115 | var seen = Set<String>() |
| 116 | return (warnings + saved).filter { seen.insert($0).inserted } |
| 117 | } |
| 118 | |
| 119 | private func overview(_ report: AnalyticsReport, state: WorkspaceRecord?) -> some View { |
| 120 | let likes = report.total(.likes) |
| 121 | let replies = report.total(.replies) |
| 122 | let importCount = report.posts.isEmpty && (state?["postsAt"] ?? "").isEmpty ? nil : report.posts.count.formatted() |
| 123 | let firstDate = report.oldestPostAt?.formatted(date: .abbreviated, time: .omitted) |
| 124 | let lastSnapshot = report.latestFollowers?.at.formatted(date: .abbreviated, time: .omitted) |
| 125 | return LazyVGrid(columns: Array(repeating: GridItem(.flexible(minimum: 95)), count: 4), spacing: 12) { |
| 126 | metric("Followers", report.latestFollowers?.count.formatted(), |
| 127 | detail: report.growth.map { value in |
| 128 | (value >= 0 ? "+" : "") + formatted(value) + " in range" |
| 129 | } ?? lastSnapshot.map { "Saved \($0)" } ?? "Awaiting first snapshot") |
| 130 | metric("Imported posts", importCount, detail: firstDate.map { "Oldest \($0)" } ?? "In selected range") |
| 131 | metric("Likes", likes.value.map(formatted), detail: coverage(likes.covered, of: report.posts.count)) |
| 132 | metric(AnalyticsReport.Metric.replies.label(for: platform), replies.value.map(formatted), |
| 133 | detail: coverage(replies.covered, of: report.posts.count)) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | private func metric(_ label: String, _ value: String?, detail: String) -> some View { |
| 138 | GroupBox { |
| 139 | VStack(alignment: .leading, spacing: 5) { |
| 140 | Text(label).font(.caption).foregroundStyle(.secondary) |
| 141 | Text(value ?? "—").font(.title2.weight(.semibold)).monospacedDigit() |
| 142 | Text(detail).font(.caption2).foregroundStyle(.secondary) |
| 143 | } |
| 144 | .frame(maxWidth: .infinity, alignment: .leading) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | private func followerChart(_ report: AnalyticsReport) -> some View { |
| 149 | GroupBox("Follower growth") { |
| 150 | if report.followers.isEmpty { |
| 151 | ContentUnavailableView("No saved observations in this range", systemImage: "chart.line.uptrend.xyaxis") |
| 152 | } else if report.followers.count == 1, let baseline = report.followers.first { |
| 153 | LabeledContent("First snapshot", value: "\(baseline.count.formatted()) on \(baseline.at.formatted(date: .abbreviated, time: .omitted))") |
| 154 | } else { |
| 155 | Chart(report.followers) { point in |
| 156 | LineMark(x: .value("Date", point.at), y: .value("Followers", point.count)) |
| 157 | .foregroundStyle(palette.accent) |
| 158 | PointMark(x: .value("Date", point.at), y: .value("Followers", point.count)) |
| 159 | .foregroundStyle(palette.accent) |
| 160 | } |
| 161 | .chartYScale(domain: .automatic(includesZero: false)) |
| 162 | .frame(height: 190) |
| 163 | DisclosureGroup("Saved follower counts") { |
| 164 | ForEach(report.followers.reversed()) { point in |
| 165 | LabeledContent(point.at.formatted(date: .abbreviated, time: .shortened), value: point.count.formatted()) |
| 166 | .font(.callout) |
| 167 | } |
| 168 | } |
| 169 | Text("The line connects saved snapshots. Days between snapshots have no observation.") |
| 170 | .font(.caption).foregroundStyle(.secondary) |
| 171 | } |
| 172 | } |
| 173 | .frame(maxWidth: .infinity, alignment: .leading) |
| 174 | } |
| 175 | |
| 176 | private func activityChart(_ report: AnalyticsReport) -> some View { |
| 177 | GroupBox("Published with Inkspring") { |
| 178 | if report.activity.isEmpty { |
| 179 | Text("No confirmed posts in this range.").foregroundStyle(.secondary) |
| 180 | .frame(maxWidth: .infinity, alignment: .leading) |
| 181 | } else { |
| 182 | Chart(report.activity) { day in |
| 183 | BarMark(x: .value("Date", day.day, unit: .day), y: .value("Posts", day.count)) |
| 184 | .foregroundStyle(palette.accent) |
| 185 | } |
| 186 | .environment(\.timeZone, TimeZone(secondsFromGMT: 0)!) |
| 187 | .frame(height: 145) |
| 188 | Text("\(report.confirmedCount) confirmed posts · \(report.replyCount) replies · UTC") |
| 189 | .font(.caption).foregroundStyle(.secondary) |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | private func rankedPosts(_ report: AnalyticsReport) -> some View { |
| 195 | VStack(alignment: .leading, spacing: 12) { |
| 196 | HStack { |
| 197 | Text("Top posts").font(.headline) |
| 198 | Spacer() |
| 199 | StudioChoicePicker(title: "Rank by", selection: $sort, |
| 200 | options: AnalyticsReport.Metric.allCases.filter { $0 != .score || platform == .reddit }, |
| 201 | label: { $0.label(for: platform) }) |
| 202 | } |
| 203 | if report.posts.isEmpty { Text("No imported posts in this range.").foregroundStyle(.secondary) } |
| 204 | ForEach(report.posts.prefix(50)) { post in |
| 205 | VStack(alignment: .leading, spacing: 6) { |
| 206 | HStack { |
| 207 | Text(post.publishedAt, format: .dateTime.month(.abbreviated).day().year()) |
| 208 | Spacer() |
| 209 | if let observed = post.observedAt { |
| 210 | Text("Metrics refreshed \(observed.formatted(date: .abbreviated, time: .shortened))") |
| 211 | } |
| 212 | } |
| 213 | .font(.caption).foregroundStyle(.secondary) |
| 214 | Text(post.record.body.isEmpty ? "Media post" : post.record.body) |
| 215 | .frame(maxWidth: .infinity, alignment: .leading) |
| 216 | HStack(spacing: 12) { |
| 217 | let metrics: [AnalyticsReport.Metric] = platform == .reddit ? [.score, .replies] : [.likes, .replies, .shares, .views] |
| 218 | ForEach(metrics) { metric in |
| 219 | Text(metric.label(for: platform) + " " + (post.value(metric).map(formatted) ?? "—")) |
| 220 | } |
| 221 | } |
| 222 | .font(.caption).foregroundStyle(.secondary) |
| 223 | if let link = URL(string: post.record["url"]), link.scheme == "https", link.host != nil, |
| 224 | link.user == nil, link.password == nil { |
| 225 | StudioExternalLink("View on \(platform.name)", destination: link).font(.caption) |
| 226 | } |
| 227 | } |
| 228 | Divider() |
| 229 | } |
| 230 | if report.posts.count > 50 { |
| 231 | Text("Showing the top 50 of \(report.posts.count) imported posts.").font(.caption).foregroundStyle(.secondary) |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | private func accountName(_ id: String, connected: ManagedSocialAccount?, distinguish: Bool) -> String { |
| 237 | if let connected, connected.id == id { return connected.username.isEmpty ? connected.name : connected.username } |
| 238 | if let receipt = workspace.records.first(where: { |
| 239 | $0.kind == "publication" && $0["platform"] == platform.rawValue && $0["accountId"] == id && !$0["accountName"].isEmpty |
| 240 | }) { |
| 241 | return receipt["accountName"] |
| 242 | } |
| 243 | return "Saved \(platform.name) account" + (distinguish ? " · " + id.suffix(4) : "") |
| 244 | } |
| 245 | |
| 246 | private func coverage(_ count: Int, of total: Int) -> String { "\(count) of \(total) posts" } |
| 247 | |
| 248 | private func formatted(_ value: Double) -> String { value.formatted(.number.precision(.fractionLength(0))) } |
| 249 | |
| 250 | private func refresh(older: Bool = false) async { |
| 251 | let selected = platform |
| 252 | let selection = accountSelection |
| 253 | do { |
| 254 | let messages = try await analytics.refresh(selected, older: older) |
| 255 | if selected == platform, selection == accountSelection { warnings = messages } |
| 256 | } catch { workspace.error = error.localizedDescription } |
| 257 | } |
| 258 | } |