Graphley / app · graphley.ai / Sources / AnalyticsUI / PortfolioBoard.swift
| 1 | import SwiftUI |
| 2 | import AnalyticsKit |
| 3 | |
| 4 | extension EnvironmentValues { |
| 5 | /// One column, card rows instead of tables (iPhone). |
| 6 | @Entry var boardCompact = false |
| 7 | } |
| 8 | |
| 9 | /// Draws a dashboard's widgets: wide ones take a row, narrow ones sit two to a row (one column on iPhone). |
| 10 | public struct DashboardBoard: View { |
| 11 | let data: PortfolioData |
| 12 | let dashboard: Dashboard |
| 13 | let compact: Bool |
| 14 | public init(data: PortfolioData, dashboard: Dashboard, compact: Bool = false) { self.data = data; self.dashboard = dashboard; self.compact = compact } |
| 15 | |
| 16 | public var body: some View { |
| 17 | VStack(alignment: .leading, spacing: compact ? 12 : 16) { |
| 18 | ForEach(Array(rows.enumerated()), id: \.offset) { _, row in |
| 19 | if row.count == 2 && !compact { |
| 20 | HStack(alignment: .top, spacing: 16) { ForEach(row) { WidgetCard(data: data, widget: $0) } } |
| 21 | } else { |
| 22 | ForEach(row) { WidgetCard(data: data, widget: $0) } |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | .environment(\.boardCompact, compact) |
| 27 | } |
| 28 | |
| 29 | var rows: [[AnalyticsKit.Widget]] { |
| 30 | var out: [[AnalyticsKit.Widget]] = [] |
| 31 | var pending: AnalyticsKit.Widget? |
| 32 | for w in dashboard.widgets { |
| 33 | if w.wide == false { |
| 34 | if let p = pending { out.append([p, w]); pending = nil } else { pending = w } |
| 35 | } else { |
| 36 | if let p = pending { out.append([p]); pending = nil } |
| 37 | out.append([w]) |
| 38 | } |
| 39 | } |
| 40 | if let p = pending { out.append([p]) } |
| 41 | return out |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | struct WidgetCard: View { |
| 46 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 47 | var body: some View { |
| 48 | TideCard(widget.title, subtitle: widget.subtitle ?? "Last \(widget.days) days") { |
| 49 | WidgetBody(data: data, widget: widget) |
| 50 | } |
| 51 | .frame(maxHeight: .infinity, alignment: .top) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | struct WidgetBody: View { |
| 56 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 57 | var days: [String] { DayKey.lastDays(widget.days) } |
| 58 | var body: some View { |
| 59 | switch widget.kind { |
| 60 | case .kpiRow: KPIRowWidget(data: data, widget: widget) |
| 61 | case .stackedArea, .area, .line: SiteStackWidget(data: data, widget: widget) |
| 62 | case .stackedBars: StackBarsWidget(data: data, widget: widget) |
| 63 | case .notes: NotesWidget(data: data, widget: widget) |
| 64 | case .siteScorecard: ScorecardWidget(data: data, widget: widget) |
| 65 | case .appPlatforms: AppPlatformsWidget(data: data, widget: widget) |
| 66 | case .ratings: RatingsWidget(data: data, widget: widget) |
| 67 | case .downloadButtons: ButtonsWidget(data: data, widget: widget) |
| 68 | case .breakdown: BreakdownWidget(data: data, widget: widget) |
| 69 | case .aiVisits: AIVisitsWidget(data: data, widget: widget) |
| 70 | case .siteDetail: SiteDetailWidget(data: data, widget: widget) |
| 71 | case .search: SearchWidget(data: data, widget: widget) |
| 72 | case .followers: FollowersWidget(data: data, widget: widget) |
| 73 | case .videos: VideosWidget(data: data, widget: widget) |
| 74 | case .ads: AdsWidget(data: data, widget: widget) |
| 75 | case .funnel: FunnelWidget(data: data, widget: widget) |
| 76 | case .number: |
| 77 | let all = DayKey.lastDays(widget.days * 2) |
| 78 | let subjects = widget.subjects.isEmpty ? nil : widget.subjects |
| 79 | let cur = data.sum(widget.metric, subjects: subjects, days: Array(all.suffix(widget.days))) |
| 80 | let prev = data.sum(widget.metric, subjects: subjects, days: Array(all.prefix(widget.days))) |
| 81 | KPITile(widget.metric.title, value: cur, previous: prev, footer: "vs previous \(widget.days) days") |
| 82 | case .ranking, .table: |
| 83 | BarList(data.sites.filter { widget.subjects.isEmpty || widget.subjects.contains($0.id) } |
| 84 | .map { ($0.name, data.sum(widget.metric, subjects: [$0.id], days: days)) }.filter { $0.1 > 0 }.sorted { $0.1 > $1.1 }.prefix(8).map { $0 }) |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // MARK: Shared pieces |
| 90 | |
| 91 | /// A table on the Mac and iPad; on iPhone each row becomes a small card with label and value pairs. |
| 92 | struct MiniTable: View { |
| 93 | struct Row: Identifiable { var id: String; var title: String; var detail: String? = nil; var color: Color? = nil; var cells: [String]; var bold = false } |
| 94 | let columns: [String] |
| 95 | let rows: [Row] |
| 96 | var firstWidth: CGFloat = 220 |
| 97 | @Environment(\.boardCompact) private var compact |
| 98 | |
| 99 | var body: some View { |
| 100 | if rows.isEmpty { |
| 101 | Text("Nothing yet. Numbers appear after the next refresh.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 102 | } else if compact { |
| 103 | cards |
| 104 | } else { |
| 105 | ViewThatFits(in: .horizontal) { grid; cards } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | var cards: some View { |
| 110 | VStack(spacing: 10) { |
| 111 | ForEach(rows) { r in |
| 112 | VStack(alignment: .leading, spacing: 8) { |
| 113 | title(r) |
| 114 | LazyVGrid(columns: compact ? Array(repeating: GridItem(.flexible(), alignment: .leading), count: 3) : [GridItem(.adaptive(minimum: 110), alignment: .leading)], spacing: 8) { |
| 115 | ForEach(Array(zip(columns, r.cells).enumerated()), id: \.offset) { _, pair in |
| 116 | VStack(alignment: .leading, spacing: 1) { |
| 117 | Text(pair.0).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1) |
| 118 | Text(pair.1).font(Tide.figure(13, medium: r.bold)).foregroundStyle(Tide.ink).lineLimit(1).minimumScaleFactor(0.7) |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | .padding(12).frame(maxWidth: .infinity, alignment: .leading) |
| 124 | .background(Tide.sunk.opacity(0.6), in: RoundedRectangle(cornerRadius: 10)) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | var grid: some View { |
| 130 | Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 9) { |
| 131 | GridRow { |
| 132 | Text("").frame(minWidth: firstWidth, idealWidth: firstWidth, maxWidth: .infinity, alignment: .leading) |
| 133 | ForEach(columns, id: \.self) { Text($0).font(Tide.sectionLabel).foregroundStyle(Tide.muted).textCase(.uppercase).gridColumnAlignment(.trailing) } |
| 134 | } |
| 135 | ForEach(rows) { r in |
| 136 | Rectangle().fill(Tide.line).frame(height: 1).gridCellUnsizedAxes(.horizontal) |
| 137 | GridRow { |
| 138 | title(r).frame(minWidth: firstWidth, idealWidth: firstWidth, maxWidth: .infinity, alignment: .leading) |
| 139 | ForEach(Array(r.cells.enumerated()), id: \.offset) { _, c in |
| 140 | Text(c).font(Tide.figure(12.5, medium: r.bold)).foregroundStyle(Tide.ink).lineLimit(1) |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | func title(_ r: Row) -> some View { |
| 148 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 149 | if let c = r.color { RoundedRectangle(cornerRadius: 2).fill(c).frame(width: 9, height: 9) } |
| 150 | VStack(alignment: .leading, spacing: 2) { |
| 151 | Text(r.title).font(r.bold ? Tide.sans(Tide.phone ? 15 : 13, .semibold) : Tide.rowTitle).foregroundStyle(Tide.ink).lineLimit(2) |
| 152 | if let d = r.detail, !d.isEmpty { Text(d).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(3).fixedSize(horizontal: false, vertical: true) } |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// A row of pills for picking one option (a site), custom like the range selector. Scrolls when it overflows. |
| 159 | struct ChipSelector: View { |
| 160 | @Binding var selection: String |
| 161 | let options: [(id: String, title: String)] |
| 162 | var body: some View { |
| 163 | ScrollView(.horizontal, showsIndicators: false) { |
| 164 | HStack(spacing: 6) { |
| 165 | ForEach(options, id: \.id) { o in Chip(title: o.title, selected: selection == o.id) { selection = o.id } } |
| 166 | } |
| 167 | .padding(1) |
| 168 | } |
| 169 | } |
| 170 | struct Chip: View { |
| 171 | let title: String, selected: Bool, action: () -> Void |
| 172 | @State private var hover = false |
| 173 | var body: some View { |
| 174 | Button(action: action) { |
| 175 | Text(title).font(Tide.sans(Tide.phone ? 13.5 : 12, .medium)) |
| 176 | .foregroundStyle(selected ? Tide.accentInk : hover ? Tide.ink : Tide.pillText) |
| 177 | .padding(.horizontal, Tide.phone ? 12 : 10).frame(height: Tide.phone ? 32 : 24) |
| 178 | .background(selected ? Tide.fill : hover ? Tide.surface2 : Tide.sunk, in: Capsule()) |
| 179 | .overlay(Capsule().strokeBorder(selected ? .clear : Tide.line)) |
| 180 | .contentShape(Capsule()) |
| 181 | } |
| 182 | .buttonStyle(.plain) |
| 183 | .onHover { hover = $0 } |
| 184 | .accessibilityAddTraits(selected ? .isSelected : []) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | struct BarColumns: View { |
| 190 | let lists: [(String, [(String, Double)])] |
| 191 | @Environment(\.boardCompact) private var compact |
| 192 | var body: some View { |
| 193 | let visible = lists.filter { !$0.1.isEmpty } |
| 194 | if visible.isEmpty { |
| 195 | Text("No events in the last 30 days.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 196 | } else { |
| 197 | LazyVGrid(columns: compact ? [GridItem(.flexible())] : [GridItem(.flexible(), spacing: 24, alignment: .top), GridItem(.flexible(), alignment: .top)], alignment: .leading, spacing: 18) { |
| 198 | ForEach(visible, id: \.0) { title, rows in |
| 199 | VStack(alignment: .leading, spacing: 8) { |
| 200 | Text(title).font(Tide.sectionLabel).foregroundStyle(Tide.muted).textCase(.uppercase) |
| 201 | BarList(Array(rows.prefix(8))) |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | enum Fmt { |
| 210 | static func money(_ v: Double) -> String { v.formatted(.currency(code: "USD").precision(.fractionLength(v < 100 ? 2 : 0))) } |
| 211 | static func pct(_ v: Double) -> String { v.isFinite ? v.formatted(.percent.precision(.fractionLength(1))) : "–" } |
| 212 | static func delta(_ cur: Double, _ prev: Double) -> String { |
| 213 | guard prev > 0 else { return cur > 0 ? "new" : "–" } |
| 214 | let p = Int(((cur - prev) / prev * 100).rounded()) |
| 215 | return p >= 0 ? "+\(p)%" : "−\(abs(p))%" |
| 216 | } |
| 217 | static func short(_ day: String) -> String { TrendChartDay.date(day).formatted(.dateTime.month(.abbreviated).day()) } |
| 218 | } |
| 219 | |
| 220 | /// Top `limit` series by total; the rest folded into one gray "Other". |
| 221 | func topSeries(_ named: [(id: String, name: String, color: Color, values: [Double])], limit: Int = 6) -> [StackedChart.Series] { |
| 222 | let sorted = named.filter { $0.values.reduce(0, +) > 0 }.sorted { $0.values.reduce(0, +) > $1.values.reduce(0, +) } |
| 223 | var out = sorted.prefix(limit).map { StackedChart.Series(id: $0.id, name: $0.name, color: $0.color, values: $0.values) } |
| 224 | let rest = sorted.dropFirst(limit) |
| 225 | if let first = rest.first { |
| 226 | let sum = rest.dropFirst().reduce(first.values) { zip($0, $1.values).map(+) } |
| 227 | out.append(.init(id: "other", name: "Other", color: Tide.other, values: sum)) |
| 228 | } |
| 229 | return out |
| 230 | } |
| 231 | |
| 232 | // MARK: Portfolio overview |
| 233 | |
| 234 | struct KPIRowWidget: View { |
| 235 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 236 | @Environment(\.boardCompact) private var compact |
| 237 | var body: some View { |
| 238 | let all = DayKey.lastDays(60), cur = Array(all.suffix(30)), prev = Array(all.prefix(30)) |
| 239 | let tiles: [(String, Double, Double)] = (widget.items ?? []).compactMap { item in |
| 240 | switch item { |
| 241 | case "visitors": |
| 242 | let v = data.sites.map { data.visitors($0.id) } |
| 243 | return ("Visitors", v.map(\.current).reduce(0, +), v.map(\.previous).reduce(0, +)) |
| 244 | case "appDownloads": return ("App Store downloads", data.sum(.appDownloads, days: cur), data.sum(.appDownloads, days: prev)) |
| 245 | case "macInstaller": return ("Mac installer downloads", data.sum(.keyEvent, days: cur, events: ["mac_installer_download"]), data.sum(.keyEvent, days: prev, events: ["mac_installer_download"])) |
| 246 | case "appStoreButton": |
| 247 | let e: Set<String> = ["app_store_click", "download_click_ios"] |
| 248 | return ("App Store button clicks", data.sum(.keyEvent, days: cur, events: e), data.sum(.keyEvent, days: prev, events: e)) |
| 249 | case "followers": |
| 250 | let l = data.socials.compactMap { data.latest(.followers, $0.id) } |
| 251 | return ("Followers", l.map(\.value).reduce(0, +), l.map { $0.previous ?? $0.value }.reduce(0, +)) |
| 252 | default: return nil |
| 253 | } |
| 254 | } |
| 255 | let cells = ForEach(tiles, id: \.0) { KPITile($0.0, value: $0.1, previous: $0.2, footer: "vs 30 days before").frame(maxHeight: .infinity, alignment: .top) } |
| 256 | // One even row when it fits, otherwise three or two to a row. |
| 257 | ViewThatFits(in: .horizontal) { |
| 258 | if !compact { HStack(alignment: .top, spacing: 10) { ForEach(tiles, id: \.0) { KPITile($0.0, value: $0.1, previous: $0.2, footer: "vs 30 days before").frame(minWidth: 150).frame(maxHeight: .infinity, alignment: .top) } }.fixedSize(horizontal: false, vertical: true) } |
| 259 | if !compact { LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 3), spacing: 10) { cells } } |
| 260 | LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 2), spacing: 10) { cells } |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | struct SiteStackWidget: View { |
| 266 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 267 | var body: some View { |
| 268 | let days = DayKey.lastDays(widget.days) |
| 269 | let sites = data.sites.filter { widget.subjects.isEmpty || widget.subjects.contains($0.id) } |
| 270 | StackedChart(days: days, series: topSeries(sites.map { ($0.id, $0.name, Tide.color(for: $0), data.daily(widget.metric, subjects: [$0.id], days: days)) })) |
| 271 | .frame(height: Tide.phone ? 200 : 230) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | struct StackBarsWidget: View { |
| 276 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 277 | static let platformOrder = ["iPhone", "iPad", "Mac", "Vision Pro", "Apple TV", "Apple Watch"] |
| 278 | var body: some View { |
| 279 | let days = DayKey.lastDays(widget.days) |
| 280 | let series: [StackedChart.Series] = { |
| 281 | if widget.breakdown == "platform" { |
| 282 | let fam = data.dailyFamily(widget.metric, family: "platform", days: days) |
| 283 | let names = fam.keys.sorted { (Self.platformOrder.firstIndex(of: $0) ?? 99, $0) < (Self.platformOrder.firstIndex(of: $1) ?? 99, $1) } |
| 284 | return names.enumerated().map { i, n in .init(id: n, name: n, color: Tide.series[i % 6], values: fam[n]!) } |
| 285 | } |
| 286 | let events = widget.event.map { Set([$0]) } |
| 287 | return topSeries(data.sites.map { ($0.id, $0.name, Tide.color(for: $0), data.daily(widget.metric, subjects: [$0.id], days: days, events: events)) }) |
| 288 | }() |
| 289 | let total = series.flatMap(\.values).reduce(0, +) |
| 290 | VStack(alignment: .leading, spacing: 8) { |
| 291 | Text("\(Tide.number(total)) in \(widget.days) days").font(Tide.figure(13, medium: true)).foregroundStyle(Tide.ink) |
| 292 | StackedChart(days: days, series: series, bars: true).frame(height: Tide.phone ? 180 : 200) |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | struct NotesWidget: View { |
| 298 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 299 | var body: some View { |
| 300 | let notes = data.caveats.filter { widget.subjects.isEmpty || $0.subjects.isEmpty || !Set($0.subjects).isDisjoint(with: widget.subjects) } |
| 301 | VStack(alignment: .leading, spacing: 10) { |
| 302 | ForEach(notes) { c in |
| 303 | HStack(alignment: .firstTextBaseline, spacing: 9) { |
| 304 | Image(systemName: "info.circle").font(.system(size: 12, weight: .medium)).foregroundStyle(Tide.attention) |
| 305 | Text(c.text).font(Tide.secondary).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true) |
| 306 | } |
| 307 | } |
| 308 | if notes.isEmpty { Text("No notes for these numbers.").font(Tide.secondary).foregroundStyle(Tide.muted) } |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // MARK: Every site |
| 314 | |
| 315 | struct ScorecardWidget: View { |
| 316 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 317 | var body: some View { |
| 318 | let all = DayKey.lastDays(60), cur = Array(all.suffix(30)) |
| 319 | let downloads = Set(Portfolio.downloadEvents) |
| 320 | let rows = data.sites.map { s -> MiniTable.Row in |
| 321 | let v = data.visitors(s.id) |
| 322 | var title = s.name |
| 323 | if s.parentID != nil, let p = s.pathPrefix { title += " (\(p))" } |
| 324 | return .init(id: s.id, title: title, detail: s.trackingNote, color: Tide.color(for: s), cells: [ |
| 325 | Tide.number(v.current), Fmt.delta(v.current, v.previous), |
| 326 | Tide.number(data.sum(.sessions, subjects: [s.id], days: cur)), Tide.number(data.sum(.pageViews, subjects: [s.id], days: cur)), |
| 327 | Tide.number(data.sum(.keyEvent, subjects: [s.id], days: cur, events: ["mac_installer_download"])), |
| 328 | Tide.number(data.sum(.keyEvent, subjects: [s.id], days: cur, events: downloads.subtracting(["mac_installer_download"]))) |
| 329 | ]) |
| 330 | } |
| 331 | MiniTable(columns: ["Visitors", "Change", "Sessions", "Page views", "Mac installs", "Buttons"], rows: rows, firstWidth: 300) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | // MARK: App Store |
| 336 | |
| 337 | struct AppPlatformsWidget: View { |
| 338 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 339 | var body: some View { |
| 340 | let days = DayKey.lastDays(widget.days) |
| 341 | let order = ["iPhone", "iPad", "Mac", "Vision Pro", "Mac (website)"] |
| 342 | let rows = data.apps.map { app -> MiniTable.Row in |
| 343 | let fam = data.dailyFamily(.appDownloads, family: "platform", subjects: [app.id], days: days).mapValues { $0.reduce(0, +) } |
| 344 | let platforms = app.platforms ?? [] |
| 345 | let cells = order.map { p -> String in |
| 346 | if p == "Mac (website)" { |
| 347 | guard platforms.contains(p), let site = app.siteID else { return "–" } |
| 348 | return Tide.number(data.sum(.keyEvent, subjects: [site], days: days, events: ["mac_installer_download"])) |
| 349 | } |
| 350 | guard app.hasAppStoreListing, platforms.contains(p) || fam[p] != nil else { return "–" } |
| 351 | return Tide.number(fam[p] ?? 0) |
| 352 | } |
| 353 | let redownloads = app.hasAppStoreListing ? Tide.number(data.sum(.appRedownloads, subjects: [app.id], days: days)) : "–" |
| 354 | return .init(id: app.id, title: app.shortName, detail: app.note, color: app.siteID.flatMap(data.site).map(Tide.color(for:)), cells: cells + [redownloads]) |
| 355 | } |
| 356 | MiniTable(columns: order + ["Redownloads"], rows: rows, firstWidth: 280) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | struct RatingsWidget: View { |
| 361 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 362 | var body: some View { |
| 363 | let listed = data.apps.filter(\.hasAppStoreListing) |
| 364 | VStack(alignment: .leading, spacing: 14) { |
| 365 | ForEach(listed) { app in |
| 366 | let r = data.latest(.rating, app.id), n = data.latest(.ratingCount, app.id) |
| 367 | HStack(alignment: .firstTextBaseline) { |
| 368 | Text(app.shortName).font(Tide.rowTitle).foregroundStyle(Tide.ink) |
| 369 | Spacer() |
| 370 | if let r, (n?.value ?? 0) > 0 { |
| 371 | Text(r.value.formatted(.number.precision(.fractionLength(1))) + " ★").font(Tide.figure(14, medium: true)).foregroundStyle(Tide.ink) |
| 372 | Text("\(Tide.number(n?.value ?? 0)) ratings").font(Tide.caption).foregroundStyle(Tide.muted) |
| 373 | } else { |
| 374 | Text("No ratings yet").font(Tide.caption).foregroundStyle(Tide.muted) |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | RowDivider() |
| 379 | Text("Newest reviews").font(Tide.sectionLabel).foregroundStyle(Tide.muted).textCase(.uppercase) |
| 380 | if data.reviews.isEmpty { |
| 381 | Text("No written reviews yet. Each new one becomes an OpenTalon to-do.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 382 | } |
| 383 | ForEach(data.reviews.sorted { $0.date > $1.date }.prefix(5)) { r in |
| 384 | VStack(alignment: .leading, spacing: 3) { |
| 385 | HStack(spacing: 6) { |
| 386 | Text(String(repeating: "★", count: r.stars) + String(repeating: "☆", count: max(0, 5 - r.stars))).font(Tide.figure(12)).foregroundStyle(Tide.attention) |
| 387 | Text(r.title).font(Tide.rowTitle).foregroundStyle(Tide.ink).lineLimit(1) |
| 388 | } |
| 389 | Text("\(r.appName.components(separatedBy: ":").first ?? r.appName) · \(r.country.uppercased()) · \(Fmt.short(r.date))").font(Tide.caption).foregroundStyle(Tide.muted) |
| 390 | if !r.text.isEmpty { Text(r.text).font(Tide.secondary).foregroundStyle(Tide.ink2).lineLimit(3) } |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // MARK: Website downloads |
| 398 | |
| 399 | struct ButtonsWidget: View { |
| 400 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 401 | var body: some View { |
| 402 | let days = DayKey.lastDays(widget.days) |
| 403 | let events = widget.items ?? Portfolio.downloadEvents |
| 404 | let names = ["mac_installer_download": "Mac installer", "download_click_mac": "Page button", "app_store_click": "App Store", "download_click_ios": "App Store (iOS)", |
| 405 | "source_click": "Source click", "source_download": "Source download"] |
| 406 | var rows = data.sites.compactMap { s -> MiniTable.Row? in |
| 407 | let values = events.map { data.sum(.keyEvent, subjects: [s.id], days: days, events: [$0]) } |
| 408 | guard values.reduce(0, +) > 0 else { return nil } |
| 409 | return .init(id: s.id, title: s.name, color: Tide.color(for: s), cells: values.map(Tide.number)) |
| 410 | } |
| 411 | if !rows.isEmpty { |
| 412 | rows.append(.init(id: "total", title: "Total", cells: events.map { Tide.number(data.sum(.keyEvent, days: days, events: [$0])) }, bold: true)) |
| 413 | } |
| 414 | return MiniTable(columns: events.map { names[$0] ?? Portfolio.eventTitle($0) }, rows: rows) |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // MARK: Pages and sources |
| 419 | |
| 420 | struct BreakdownWidget: View { |
| 421 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 422 | @State private var pick = "all" |
| 423 | var body: some View { |
| 424 | let family = widget.breakdown ?? "page" |
| 425 | let engine: String? = [.searchClicks, .searchImpressions].contains(widget.metric) ? "google" : nil |
| 426 | let withData = data.sites.filter { !data.window(widget.metric, family: family, subject: $0.id, engine: engine).isEmpty } |
| 427 | let subjects = pick == "all" ? withData.map(\.id) : [pick] |
| 428 | let prefixSite = pick == "all" && ["page", "spage"].contains(family) |
| 429 | let rows = data.windowTotals(widget.metric, family: family, subjects: subjects, engine: engine) { label, _, subject in |
| 430 | prefixSite ? "\(data.name(subject)) \(label)" : label |
| 431 | } |
| 432 | VStack(alignment: .leading, spacing: 12) { |
| 433 | if withData.count > 1 { |
| 434 | ChipSelector(selection: $pick, options: [("all", "All sites")] + withData.map { ($0.id, $0.name) }) |
| 435 | } |
| 436 | if rows.isEmpty { Text("Nothing yet. Numbers appear after the next refresh.").font(Tide.secondary).foregroundStyle(Tide.muted) } |
| 437 | BarList(Array(rows.prefix(10))) |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | struct AIVisitsWidget: View { |
| 443 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 444 | @Environment(\.boardCompact) private var compact |
| 445 | var body: some View { |
| 446 | let days = DayKey.lastDays(widget.days) |
| 447 | let fam = data.dailyFamily(.sessions, family: "ai", days: days) |
| 448 | let series = topSeries(fam.keys.sorted().enumerated().map { i, k in (k, k, Tide.series[i % 6], fam[k]!) }) |
| 449 | let bySite = data.sites.map { s in (s.name, data.dailyFamily(.sessions, family: "ai", subjects: [s.id], days: days).values.flatMap { $0 }.reduce(0, +)) } |
| 450 | .filter { $0.1 > 0 }.sorted { $0.1 > $1.1 } |
| 451 | let landings = data.windowTotals(.sessions, family: "ailanding", subjects: data.sites.map(\.id)) { l, _, s in "\(data.name(s)) \(l)" } |
| 452 | VStack(alignment: .leading, spacing: 16) { |
| 453 | Text("\(Tide.number(series.flatMap(\.values).reduce(0, +))) sessions in \(widget.days) days").font(Tide.figure(13, medium: true)).foregroundStyle(Tide.ink) |
| 454 | if !series.isEmpty { StackedChart(days: days, series: series, bars: true).frame(height: 180) } |
| 455 | BarColumns(lists: [("By site", bySite), ("Landing pages, last 30 days", Array(landings.prefix(8)))]) |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | // MARK: Site detail |
| 461 | |
| 462 | struct SiteDetailWidget: View { |
| 463 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 464 | static let families: [(String, String)] = [("section", "Clicks by section"), ("domain", "Click-outs by domain"), ("cta", "Buttons (CTA)"), |
| 465 | ("scroll", "Scroll depth"), ("form", "Forms"), ("field", "Form left at field"), ("video", "Video"), ("file", "Files"), ("step", "Builder steps")] |
| 466 | static let tiles = ["book_call", "generate_lead", "resume_download", "resume_open", "outbound_click", "cta_click", "form_submitted", "video_play", "builder_step", "begin_checkout"] |
| 467 | @Environment(\.boardCompact) private var compact |
| 468 | var body: some View { |
| 469 | let days = DayKey.lastDays(30) |
| 470 | let counts = Self.tiles.map { ($0, data.sum(.keyEvent, subjects: widget.subjects, days: days, events: [$0])) }.filter { $0.1 > 0 } |
| 471 | let lists = Self.families.map { family, title -> (String, [(String, Double)]) in |
| 472 | let split = ["form", "video", "file"].contains(family) |
| 473 | return (title, data.windowTotals(.keyEvent, family: family, subjects: widget.subjects) { label, event, _ in |
| 474 | let l = family == "scroll" ? label + "%" : label |
| 475 | return split ? "\(l) · \(Portfolio.eventTitle(event ?? "").lowercased())" : l |
| 476 | }) |
| 477 | } |
| 478 | VStack(alignment: .leading, spacing: 14) { |
| 479 | if !counts.isEmpty { |
| 480 | LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: compact ? 2 : 4), spacing: 10) { |
| 481 | ForEach(counts, id: \.0) { e, v in |
| 482 | VStack(alignment: .leading, spacing: 2) { |
| 483 | Text(Portfolio.eventTitle(e)).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1) |
| 484 | Text(Tide.number(v)).font(Tide.display(22)).foregroundStyle(Tide.ink) |
| 485 | } |
| 486 | .frame(maxWidth: .infinity, alignment: .leading).padding(10) |
| 487 | .background(Tide.sunk, in: RoundedRectangle(cornerRadius: 9)) |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | BarColumns(lists: lists) |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | // MARK: Search |
| 497 | |
| 498 | struct SearchWidget: View { |
| 499 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 500 | func position(_ id: String, days: [String]) -> String { |
| 501 | let pos = data.points(.searchPosition, id).filter { $0.breakdown == nil && $0.event == "google" && days.contains($0.day) } |
| 502 | let imp = Dictionary(data.points(.searchImpressions, id).filter { $0.breakdown == nil && $0.event == "google" }.map { ($0.day, $0.value) }, uniquingKeysWith: { a, _ in a }) |
| 503 | let weight = pos.map { imp[$0.day] ?? 0 }.reduce(0, +) |
| 504 | guard weight > 0 else { return "–" } |
| 505 | return (zip(pos, pos.map { imp[$0.day] ?? 0 }).map { $0.value * $1 }.reduce(0, +) / weight).formatted(.number.precision(.fractionLength(1))) |
| 506 | } |
| 507 | var body: some View { |
| 508 | let days = DayKey.lastDays(widget.days) |
| 509 | let searchable = data.sites.filter { $0.searchConsoleProperty != nil || $0.bingSiteURL != nil } |
| 510 | let rows = searchable.map { s -> MiniTable.Row in |
| 511 | let gc = data.sum(.searchClicks, subjects: [s.id], days: days, engine: "google"), gi = data.sum(.searchImpressions, subjects: [s.id], days: days, engine: "google") |
| 512 | let bc = data.sum(.searchClicks, subjects: [s.id], days: days, engine: "bing"), bi = data.sum(.searchImpressions, subjects: [s.id], days: days, engine: "bing") |
| 513 | return .init(id: s.id, title: s.name, detail: s.searchConsoleProperty, color: Tide.color(for: s), cells: [ |
| 514 | Tide.number(gc), Tide.number(gi), gi > 0 ? Fmt.pct(gc / gi) : "–", position(s.id, days: days), |
| 515 | s.bingSiteURL == nil ? "–" : Tide.number(bc), s.bingSiteURL == nil ? "–" : Tide.number(bi)]) |
| 516 | } |
| 517 | VStack(alignment: .leading, spacing: 14) { |
| 518 | TrendChart(days: days, values: data.daily(.searchClicks, days: days, engine: "google"), label: "Google clicks").frame(height: 150) |
| 519 | MiniTable(columns: ["Google clicks", "Impressions", "CTR", "Position", "Bing clicks", "Bing impr."], rows: rows, firstWidth: 240) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | // MARK: Followers and videos |
| 525 | |
| 526 | struct FollowersWidget: View { |
| 527 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 528 | @Environment(\.boardCompact) private var compact |
| 529 | var body: some View { |
| 530 | let days = DayKey.lastDays(widget.days + 1, endingBefore: .now.addingTimeInterval(86_400)) |
| 531 | let total = data.socials.map { data.carried(.followers, $0.id, days: days) }.reduce(Array(repeating: 0.0, count: days.count)) { zip($0, $1).map(+) } |
| 532 | VStack(alignment: .leading, spacing: 14) { |
| 533 | if total.contains(where: { $0 > 0 }) { TrendChart(days: days, values: total, label: "Followers, every account").frame(height: 150) } |
| 534 | VStack(spacing: 0) { |
| 535 | ForEach(data.socials) { a in |
| 536 | let l = data.latest(.followers, a.id) |
| 537 | HStack(spacing: 12) { |
| 538 | VStack(alignment: .leading, spacing: 2) { |
| 539 | Text(a.title).font(Tide.rowTitle).foregroundStyle(Tide.ink) |
| 540 | Text(a.handle + (a.source == "manual" ? " · recorded by hand" : "") + (l.map { " · \(Fmt.short($0.day))" } ?? "")) |
| 541 | .font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1) |
| 542 | } |
| 543 | Spacer(minLength: 8) |
| 544 | if !compact { Sparkline(data.carried(.followers, a.id, days: days), color: Tide.accent) } |
| 545 | VStack(alignment: .trailing, spacing: 2) { |
| 546 | Text(l.map { Tide.number($0.value) } ?? "–").font(Tide.figure(14, medium: true)).foregroundStyle(Tide.ink) |
| 547 | if let l, let p = l.previous { |
| 548 | let d = l.value - p |
| 549 | Text((d >= 0 ? "+" : "−") + Tide.number(abs(d)) + " in 30 days").font(Tide.caption).foregroundStyle(d > 0 ? Tide.up : d < 0 ? Tide.down : Tide.muted) |
| 550 | } |
| 551 | } |
| 552 | .frame(minWidth: 90, alignment: .trailing) |
| 553 | } |
| 554 | .padding(.vertical, 9) |
| 555 | RowDivider() |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | struct VideosWidget: View { |
| 563 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 564 | @State private var pick = "" |
| 565 | var body: some View { |
| 566 | let channels = data.socials.filter { a in a.platform == .youtube && data.videos.contains { $0.account == a.id } } |
| 567 | let current = pick.isEmpty ? channels.first?.id ?? "" : pick |
| 568 | let mine = data.videos.filter { $0.account == current } |
| 569 | let views = Dictionary(mine.map { ($0.id, data.latest(.videoViews, $0.id)?.value ?? 0) }, uniquingKeysWith: { a, _ in a }) |
| 570 | let newest = mine.filter { $0.published != nil }.sorted { $0.published! > $1.published! }.prefix(5) |
| 571 | let top = mine.sorted { views[$0.id]! > views[$1.id]! }.prefix(10) |
| 572 | VStack(alignment: .leading, spacing: 12) { |
| 573 | if channels.count > 1 { ChipSelector(selection: Binding(get: { current }, set: { pick = $0 }), options: channels.map { ($0.id, $0.handle) }) } |
| 574 | if mine.isEmpty { Text("No videos yet. They appear after the next refresh.").font(Tide.secondary).foregroundStyle(Tide.muted) } |
| 575 | if !newest.isEmpty { list("Newest", Array(newest), views) } |
| 576 | if !top.isEmpty { list("Most viewed", Array(top), views) } |
| 577 | } |
| 578 | } |
| 579 | func list(_ title: String, _ videos: [Video], _ views: [String: Double]) -> some View { |
| 580 | VStack(alignment: .leading, spacing: 6) { |
| 581 | Text(title).font(Tide.sectionLabel).foregroundStyle(Tide.muted).textCase(.uppercase) |
| 582 | ForEach(videos) { v in |
| 583 | HStack(spacing: 8) { |
| 584 | Text(v.title).font(Tide.secondary).foregroundStyle(Tide.ink).lineLimit(1) |
| 585 | if v.kind != "video" { StatusPill(v.kind == "short" ? "Short" : "Live", .neutral) } |
| 586 | Spacer(minLength: 8) |
| 587 | if let l = data.latest(.videoLikes, v.id), l.value > 0 { Text("\(Tide.number(l.value)) likes").font(Tide.caption).foregroundStyle(Tide.muted) } |
| 588 | Text("\(Tide.number(views[v.id] ?? 0)) views").font(Tide.figure(12)).foregroundStyle(Tide.ink) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | // MARK: Ads |
| 596 | |
| 597 | struct AdsWidget: View { |
| 598 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 599 | func total(_ m: Metric, _ id: String) -> Double { data.points(m, id).filter { $0.breakdown == nil }.map(\.value).reduce(0, +) } |
| 600 | var body: some View { |
| 601 | let rows = data.campaigns.map { c -> MiniTable.Row in |
| 602 | let dates = [c.start.map(Fmt.short), c.end.map(Fmt.short)].compactMap { $0 }.joined(separator: " – ") |
| 603 | let detail = [c.platform, c.budget, dates.isEmpty ? nil : dates, c.paused.map { "paused \(Fmt.short($0))" }, c.landing.map { "→ \($0)" }, |
| 604 | "\(c.status) \(c.expired.map(Fmt.short) ?? "")"].compactMap { $0 }.joined(separator: " · ") |
| 605 | return .init(id: c.id, title: c.name, detail: detail, cells: [Fmt.money(total(.adSpend, c.id)), Tide.number(total(.adClicks, c.id)), |
| 606 | Tide.number(total(.adImpressions, c.id)), Tide.number(total(.adConversions, c.id))]) |
| 607 | } |
| 608 | let ids = data.campaigns.map(\.id) |
| 609 | let sum = { (m: Metric) in ids.map { total(m, $0) }.reduce(0, +) } |
| 610 | VStack(alignment: .leading, spacing: 12) { |
| 611 | ViewThatFits(in: .horizontal) { |
| 612 | HStack(spacing: 8) { StatusPill("All campaigns expired Nov 22", .neutral).fixedSize(); Text("No new ads are suggested.").font(Tide.caption).foregroundStyle(Tide.muted).fixedSize() } |
| 613 | VStack(alignment: .leading, spacing: 6) { StatusPill("All campaigns expired Nov 22", .neutral).fixedSize(); Text("No new ads are suggested.").font(Tide.caption).foregroundStyle(Tide.muted) } |
| 614 | } |
| 615 | MiniTable(columns: ["Spend", "Clicks", "Impressions", "Conversions"], |
| 616 | rows: rows + (rows.isEmpty ? [] : [.init(id: "total", title: "Total", cells: [Fmt.money(sum(.adSpend)), Tide.number(sum(.adClicks)), Tide.number(sum(.adImpressions)), Tide.number(sum(.adConversions))], bold: true)]), |
| 617 | firstWidth: 320) |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | struct FunnelWidget: View { |
| 623 | let data: PortfolioData, widget: AnalyticsKit.Widget |
| 624 | var body: some View { |
| 625 | let days = Set(DayKey.lastDays(widget.days)) |
| 626 | var sessions: [String: [Double]] = [:] // "site|landing|source" → sessions, engaged, CTA, write-instead, calls, leads |
| 627 | for s in widget.subjects { |
| 628 | for p in data.points(.sessions, s) + data.points(.engagedSessions, s) + data.points(.keyEvent, s) where p.family == "funnel" && days.contains(p.day) { |
| 629 | let parts = (p.breakdownValue ?? "").components(separatedBy: "|") |
| 630 | guard parts.count == 2 else { continue } |
| 631 | let key = "\(s)|\(parts[0])|\(parts[1])" |
| 632 | var row = sessions[key] ?? Array(repeating: 0, count: 6) |
| 633 | switch (p.metric, p.event) { |
| 634 | case (.sessions, _): row[0] += p.value |
| 635 | case (.engagedSessions, _): row[1] += p.value |
| 636 | case (_, "cta:book_call_open"): row[2] += p.value |
| 637 | case (_, "cta:lp_write_instead"): row[3] += p.value |
| 638 | case (_, "book_call"): row[4] += p.value |
| 639 | case (_, "generate_lead"): row[5] += p.value |
| 640 | default: break |
| 641 | } |
| 642 | sessions[key] = row |
| 643 | } |
| 644 | } |
| 645 | let sources = ["google / cpc": "Google Ads (google / cpc)", "linkedin / paid-social": "LinkedIn Ads (paid social)", "other": "Unpaid visits"] |
| 646 | let sorted = sessions.sorted { a, b in a.value[0] > b.value[0] }.prefix(14) |
| 647 | let rows = sorted.map { entry -> MiniTable.Row in |
| 648 | let p = entry.key.components(separatedBy: "|") |
| 649 | return MiniTable.Row(id: entry.key, title: "\(data.name(p[0])) \(p[1])", detail: sources[p[2]] ?? p[2], cells: entry.value.map { Tide.number($0) }) |
| 650 | } |
| 651 | return MiniTable(columns: ["Sessions", "Engaged", "Book call", "Write instead", "Calls", "Leads"], rows: Array(rows), firstWidth: 280) |
| 652 | } |
| 653 | } |