import SwiftUI import UniformTypeIdentifiers import AnalyticsKit import AnalyticsUI enum SidebarItem: Hashable { case overview, apps, dashboard(String), agents, sources, settings, site(String) } /// The main window: our own sidebar rows inside the native sidebar, and one screen on the right. /// Layout and copy follow design/DESIGN.md. struct ContentView: View { @Environment(AppModel.self) private var model var body: some View { NavigationSplitView { Sidebar() .navigationSplitViewColumnWidth(min: 200, ideal: 220) } detail: { ScrollView { screen .padding(24) .frame(maxWidth: narrow ? 728 : .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading) .background(OverlayScrollers()) } .background(Tide.surface) .navigationTitle(title) .modifier(TopBar(showsRange: showsRange)) } } @ViewBuilder var screen: some View { switch model.selection { case .overview: OverviewView() case .apps: AppStoreView() case .dashboard(let id): DashboardView(dashboardID: id) case .agents: AgentsView() case .sources: SourcesView() case .settings: SettingsView() case .site(let id): SiteView(siteID: id) } } /// Forms read best at a fixed width; data screens use the whole window. var narrow: Bool { [.sources, .settings].contains(model.selection) } /// The range only changes Overview, App Store and site screens (dashboard widgets have their own days). var showsRange: Bool { switch model.selection { case .overview, .apps, .site: true default: false } } var title: String { switch model.selection { case .overview: "Overview" case .apps: "Apps" case .dashboard(let id): model.workspace.dashboards.first { $0.id == id }?.name ?? "Dashboard" case .agents: "Agents" case .sources: "Sources & keys" case .settings: "Settings" case .site(let id): model.sites.first { $0.id == id }?.name ?? "Site" } } } // MARK: Top bar /// One calm top bar (design/DESIGN.md 2.3): the range pill and the refresh pill, both 30 pt, /// 12 pt apart, ending in line with the cards below. Our own controls, with the system glass off. /// Without the title, toolbar items flow from the leading edge, so a flexible spacer pushes ours right. struct TopBar: ViewModifier { let showsRange: Bool func body(content: Content) -> some View { if #available(macOS 26, *) { content.toolbar(removing: .title).toolbar { ToolbarSpacer(.flexible) ToolbarItem { TopBarCluster(showsRange: showsRange) } .sharedBackgroundVisibility(.hidden) } } else { content.toolbar { ToolbarItem { TopBarCluster(showsRange: showsRange) } } } } } struct TopBarCluster: View { let showsRange: Bool @Environment(AppModel.self) private var model /// Extra space after the refresh pill so it ends 24 pt from the window edge, like the cards. static let trailingNudge: CGFloat = 20 var body: some View { @Bindable var model = model HStack(spacing: 12) { if showsRange { RangeSelector(selection: $model.range) } RefreshPill(status: status, refresh: { Task { await model.refresh() } }, openSources: { model.selection = .sources }) } .padding(.trailing, Self.trailingNudge) .transaction { $0.animation = nil } } var status: RefreshPillStatus { if model.refreshing { return .refreshing } if !model.failures.isEmpty { return .failed(model.failures.count) } guard let at = model.workspace.settings.lastRefreshAt else { // Numbers can arrive without an in-app refresh (an agent, an older version), so say how fresh they are. guard let day = model.points.map(\.day).max(), let date = ISO8601DateFormatter.dayOnly.date(from: day) else { return .never } return .dataThrough(date.formatted(.dateTime.month(.abbreviated).day())) } let when = RefreshTime.describe(at) return Date.now.timeIntervalSince(at) > 26 * 3600 ? .stale(when) : .fresh(when) } } /// Keeps the detail page's scroll bar in overlay style even when a mouse makes macOS show it always, /// so the content column (and the top bar lined up with it) is the same width on every screen. struct OverlayScrollers: NSViewRepresentable { func makeNSView(context: Context) -> Probe { Probe() } func updateNSView(_ view: Probe, context: Context) { view.apply() } final class Probe: NSView { private var observing = false override func viewDidMoveToWindow() { super.viewDidMoveToWindow() apply() guard !observing else { return } observing = true NotificationCenter.default.addObserver(self, selector: #selector(styleChanged), name: NSScroller.preferredScrollerStyleDidChangeNotification, object: nil) } @objc private func styleChanged() { apply() } func apply() { // Set it after the system's own update from the same notification. DispatchQueue.main.async { [weak self] in self?.enclosingScrollView?.scrollerStyle = .overlay } } } } enum RefreshTime { static func describe(_ date: Date) -> String { let cal = Calendar.current if cal.isDateInToday(date) { return date.formatted(date: .omitted, time: .shortened) } if cal.isDateInYesterday(date) { return "yesterday" } let days = cal.dateComponents([.day], from: date, to: .now).day ?? 0 return days < 7 ? "\(days) days ago" : date.formatted(.dateTime.month(.abbreviated).day()) } } // MARK: Sidebar struct Sidebar: View { @Environment(AppModel.self) private var model /// The site being dragged to a new place in the list. @State private var dragging: String? var body: some View { VStack(spacing: 0) { ScrollView { VStack(alignment: .leading, spacing: 2) { SectionLabel("Portfolio") SidebarRow("Overview", icon: "chart.xyaxis.line", item: .overview) SidebarRow("Apps", icon: "arrow.down.app", item: .apps) ForEach(model.workspace.dashboards) { d in SidebarRow(d.name, icon: "rectangle.3.group", item: .dashboard(d.id)) } SidebarRow("Agents", icon: "terminal", item: .agents) SidebarRow("Sources & keys", icon: "key.horizontal", item: .sources) SectionLabel("Sites") if model.sites.isEmpty { VStack(alignment: .leading, spacing: 6) { Text("No sites yet").font(Tide.secondary).foregroundStyle(Tide.muted) Button("Add Sites…") { model.selection = .sources; model.wantsSitePicker = model.googleConnected } .buttonStyle(.tide(.quiet, size: .small)) } .padding(.horizontal, 10) } ForEach(model.sites) { site in SidebarRow(site.name, dot: Tide.color(for: site), count: model.total(.users, site: site.id, days: model.range), item: .site(site.id)) .opacity(dragging == site.id ? 0.35 : 1) .onDrag { dragging = site.id return NSItemProvider(object: site.id as NSString) } preview: { SiteDragPreview(site: site) } .help("Drag to change the order. Your iPhone and iPad use the same order.") .onDrop(of: [.plainText], delegate: SiteDropDelegate(target: site.id, dragging: $dragging, model: model)) .contextMenu { Button("Move Up") { withAnimation(.snappy(duration: 0.2)) { model.moveSite(site.id, by: -1) } } .disabled(model.sites.first?.id == site.id) Button("Move Down") { withAnimation(.snappy(duration: 0.2)) { model.moveSite(site.id, by: 1) } } .disabled(model.sites.last?.id == site.id) } } } .padding(.horizontal, 10).padding(.bottom, 10) // A drop in the gaps between rows still ends the drag cleanly. .onDrop(of: [.plainText], isTargeted: nil) { _ in let wasDragging = dragging != nil dragging = nil return wasDragging } } .onChange(of: model.selection) { dragging = nil } VStack(alignment: .leading, spacing: 6) { SidebarRow("Settings", icon: "gearshape", item: .settings) Label(iPhoneStatus, systemImage: "iphone").font(Tide.caption).foregroundStyle(Tide.muted) .labelStyle(SmallIconLabel()).padding(.horizontal, 10) } .padding(.horizontal, 10).padding(.vertical, 10) } .focusable() .focusEffectDisabled() .onMoveCommand { direction in move(direction) } } var iPhoneStatus: String { let s = model.workspace.settings guard s.shareWithIPhone else { return "iPhone sharing is off" } guard let at = s.lastSharedAt else { return "iPhone: not shared yet" } return "iPhone: updated \(RefreshTime.describe(at))" } var order: [SidebarItem] { [.overview, .apps] + model.workspace.dashboards.map { .dashboard($0.id) } + [.agents, .sources] + model.sites.map { .site($0.id) } + [.settings] } func move(_ direction: MoveCommandDirection) { guard let i = order.firstIndex(of: model.selection) else { return } switch direction { case .up where i > 0: model.selection = order[i - 1] case .down where i < order.count - 1: model.selection = order[i + 1] default: break } } } /// Live reordering: as the dragged site passes over another row, it takes that row's place, so the /// list shows the new order before the drop. The order is saved as it changes. struct SiteDropDelegate: DropDelegate { let target: String @Binding var dragging: String? let model: AppModel func validateDrop(info: DropInfo) -> Bool { dragging != nil } func dropEntered(info: DropInfo) { guard let dragging, dragging != target else { return } withAnimation(.snappy(duration: 0.2)) { model.moveSite(dragging, to: target) } } func dropUpdated(info: DropInfo) -> DropProposal? { DropProposal(operation: .move) } func performDrop(info: DropInfo) -> Bool { dragging = nil return true } } struct SiteDragPreview: View { let site: Site var body: some View { HStack(spacing: 8) { Circle().fill(Tide.color(for: site)).frame(width: 8, height: 8) Text(site.name).font(Tide.sans(13, .medium)).foregroundStyle(Tide.ink) } .padding(.horizontal, 12).frame(height: 28) .background(Tide.surface, in: RoundedRectangle(cornerRadius: 8)) .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Tide.line2)) } } struct SmallIconLabel: LabelStyle { func makeBody(configuration: Configuration) -> some View { HStack(spacing: 6) { configuration.icon.font(.system(size: 11)); configuration.title } } } struct SectionLabel: View { let text: String init(_ text: String) { self.text = text } var body: some View { Text(text.uppercased()).font(Tide.sectionLabel).tracking(0.8).foregroundStyle(Tide.muted) .padding(.leading, 10).padding(.top, 14).padding(.bottom, 6) .accessibilityAddTraits(.isHeader) } } struct SidebarRow: View { let title: String, icon: String?, dot: Color?, count: Double?, item: SidebarItem @Environment(AppModel.self) private var model @Environment(\.colorScheme) private var scheme @State private var hover = false init(_ title: String, icon: String? = nil, dot: Color? = nil, count: Double? = nil, item: SidebarItem) { self.title = title; self.icon = icon; self.dot = dot; self.count = count; self.item = item } var body: some View { let selected = model.selection == item Button { model.selection = item } label: { HStack(spacing: 8) { if let icon { Image(systemName: icon).font(.system(size: 14, weight: .medium)).frame(width: 18) .foregroundStyle(selected ? Tide.accentInk : Tide.muted) } else if let dot { Circle().fill(dot).frame(width: 8, height: 8).frame(width: 18) } Text(title).font(Tide.sans(13, .medium)).lineLimit(1).truncationMode(.tail) .foregroundStyle(selected ? Tide.accentInk : Tide.ink) Spacer(minLength: 4) if let count { Text(Tide.number(count)).font(Tide.figure(11.5)) .foregroundStyle(selected ? Tide.accentInk.opacity(0.75) : Tide.muted) } } .padding(.horizontal, 10) .frame(height: 28) .background(selected ? Tide.fill : hover ? (scheme == .dark ? Tide.surface2 : Tide.sunk) : .clear, in: RoundedRectangle(cornerRadius: 8)) .contentShape(RoundedRectangle(cornerRadius: 8)) } .buttonStyle(.plain) .onHover { hover = $0 } .accessibilityAddTraits(selected ? .isSelected : []) } }