Inkspring / app · inkspring.ai / native-mac / iPhone / InkspringCompanion.swift
| 1 | import CloudKit |
| 2 | import SwiftUI |
| 3 | |
| 4 | @main |
| 5 | struct InkspringCompanion: App { |
| 6 | var body: some Scene { |
| 7 | WindowGroup { MobileHome() } |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | private struct MobileHome: View { |
| 12 | private enum Tab: CaseIterable { |
| 13 | case review, ideas, schedule, published, settings |
| 14 | var title: String { |
| 15 | switch self { |
| 16 | case .review: "Review" |
| 17 | case .ideas: "New ideas" |
| 18 | case .schedule: "Schedule" |
| 19 | case .published: "Published" |
| 20 | case .settings: "Settings" |
| 21 | } |
| 22 | } |
| 23 | var icon: String { |
| 24 | switch self { |
| 25 | case .review: "tray" |
| 26 | case .ideas: "lightbulb" |
| 27 | case .schedule: "calendar" |
| 28 | case .published: "paperplane" |
| 29 | case .settings: "gearshape" |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | @Environment(\.scenePhase) private var scenePhase |
| 35 | @Environment(\.colorScheme) private var colorScheme |
| 36 | @AppStorage("inkspring.mobile.theme") private var theme = StudioTheme.defaultPreference |
| 37 | @State private var library = MobileLibrary() |
| 38 | @State private var schedule = MobileSchedule() |
| 39 | @State private var tab = Self.startingTab |
| 40 | |
| 41 | @AppStorage("inkspring.mobile.completedWelcome", store: MobileLibrary.preferences) private var completedWelcome = MobileHome.previouslyUsed |
| 42 | @State private var reviewingSetup = false |
| 43 | |
| 44 | private static let previouslyUsed: Bool = { |
| 45 | #if DEBUG |
| 46 | if ProcessInfo.processInfo.arguments.contains("--library-fixture") { return true } |
| 47 | if ProcessInfo.processInfo.arguments.contains("--unpaired-fixture") { return false } |
| 48 | #endif |
| 49 | return ["inkspring.mobile.libraryOutbox.v1", "inkspring.mobile.localIdeas.v1", "inkspring.mobile.draftSort"] |
| 50 | .contains { UserDefaults.standard.object(forKey: $0) != nil } |
| 51 | }() |
| 52 | |
| 53 | private func finishWelcome(_ destination: Tab) { |
| 54 | tab = destination |
| 55 | completedWelcome = true |
| 56 | reviewingSetup = false |
| 57 | } |
| 58 | |
| 59 | private static var startingTab: Tab { |
| 60 | #if DEBUG |
| 61 | let arguments = ProcessInfo.processInfo.arguments |
| 62 | if arguments.contains("--ideas-fixture") { return .ideas } |
| 63 | if arguments.contains("--schedule-fixture") { return .schedule } |
| 64 | #endif |
| 65 | return .review |
| 66 | } |
| 67 | |
| 68 | var body: some View { |
| 69 | let palette = StudioPalette(theme: theme.resolve(for: colorScheme)) |
| 70 | Group { |
| 71 | if library.snapshot == nil && library.lastCheck == nil { |
| 72 | MobileLibraryLoadingView() |
| 73 | } else if !completedWelcome || reviewingSetup { |
| 74 | MobileWelcomeView(connected: library.snapshot != nil, replay: reviewingSetup, |
| 75 | write: { finishWelcome(.ideas) }, |
| 76 | enter: { finishWelcome(reviewingSetup ? tab : .review) }) |
| 77 | } else { |
| 78 | mainLayout(palette: palette) |
| 79 | } |
| 80 | } |
| 81 | .environment(\.studioPalette, palette) |
| 82 | .labelStyle(StudioIconLabelStyle()) |
| 83 | .preferredColorScheme(theme == .system ? nil : palette.colorScheme) |
| 84 | .tint(palette.accent) |
| 85 | .onReceive(NotificationCenter.default.publisher(for: .CKAccountChanged)) { _ in |
| 86 | library.accountChanged() |
| 87 | schedule.accountChanged() |
| 88 | Task { await library.refresh() } |
| 89 | if isShowingSchedule { Task { await schedule.refresh() } } |
| 90 | } |
| 91 | .task(id: scenePhase) { |
| 92 | guard scenePhase == .active else { return } |
| 93 | while !Task.isCancelled { |
| 94 | await library.refresh() |
| 95 | do { try await Task.sleep(for: .seconds(25)) } |
| 96 | catch { return } |
| 97 | } |
| 98 | } |
| 99 | .task(id: scenePhase) { |
| 100 | guard scenePhase == .active else { return } |
| 101 | while !Task.isCancelled { |
| 102 | if isShowingSchedule { await schedule.refresh() } |
| 103 | do { try await Task.sleep(for: .seconds(30)) } |
| 104 | catch { return } |
| 105 | } |
| 106 | } |
| 107 | .onChange(of: tab) { _, _ in |
| 108 | if isShowingSchedule { Task { await schedule.refresh() } } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | private var isShowingSchedule: Bool { tab == .schedule || tab == .published } |
| 113 | |
| 114 | private func mainLayout(palette: StudioPalette) -> some View { |
| 115 | GeometryReader { geometry in |
| 116 | HStack(spacing: 0) { |
| 117 | if geometry.size.width >= 800 { |
| 118 | VStack(alignment: .leading, spacing: 10) { |
| 119 | Text("Inkspring").font(.headline).padding(.horizontal, 12).padding(.bottom, 18) |
| 120 | ForEach(Tab.allCases, id: \.self) { destination in |
| 121 | Button { tab = destination } label: { |
| 122 | Label { |
| 123 | Text(destination.title) |
| 124 | } icon: { |
| 125 | Image(systemName: destination.icon) |
| 126 | .foregroundStyle(navigationIconColor(for: destination, palette: palette)) |
| 127 | } |
| 128 | .font(.body.weight(tab == destination ? .semibold : .regular)) |
| 129 | .frame(maxWidth: .infinity, alignment: .leading) |
| 130 | .padding(12) |
| 131 | .background(tab == destination ? palette.well : .clear, in: .rect(cornerRadius: 12)) |
| 132 | } |
| 133 | .buttonStyle(.plain) |
| 134 | .accessibilityAddTraits(tab == destination ? .isSelected : []) |
| 135 | } |
| 136 | Spacer() |
| 137 | } |
| 138 | .padding(16).padding(.top, 20) |
| 139 | .frame(width: 205) |
| 140 | .background(palette.card) |
| 141 | Divider() |
| 142 | } |
| 143 | compactTabs(palette: palette) |
| 144 | .environment(\.mobileWideLayout, geometry.size.width >= 800) |
| 145 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | private func compactTabs(palette: StudioPalette) -> some View { |
| 151 | TabView(selection: $tab) { |
| 152 | MobileReviewView(library: library, isSelected: tab == .review, writeIdea: { tab = .ideas }, |
| 153 | openSetup: { reviewingSetup = true }, openSettings: { tab = .settings }) |
| 154 | .tabItem { tabLabel(.review, palette: palette) } |
| 155 | .tag(Tab.review) |
| 156 | MobileIdeasView(library: library, isSelected: tab == .ideas) |
| 157 | .tabItem { tabLabel(.ideas, palette: palette) } |
| 158 | .tag(Tab.ideas) |
| 159 | CompanionScheduleView(library: library, schedule: schedule, destination: .schedule) |
| 160 | .tabItem { tabLabel(.schedule, palette: palette) } |
| 161 | .tag(Tab.schedule) |
| 162 | CompanionScheduleView(library: library, schedule: schedule, destination: .published) |
| 163 | .tabItem { tabLabel(.published, palette: palette) } |
| 164 | .tag(Tab.published) |
| 165 | MobileSettingsView(theme: $theme, library: library, openSetup: { reviewingSetup = true }) |
| 166 | .tabItem { tabLabel(.settings, palette: palette) } |
| 167 | .tag(Tab.settings) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | private func navigationIconColor(for destination: Tab, palette: StudioPalette) -> Color { |
| 172 | if tab == destination { return palette.iconAccent } |
| 173 | return palette.dark ? .white : .black |
| 174 | } |
| 175 | |
| 176 | private func tabLabel(_ destination: Tab, palette: StudioPalette) -> some View { |
| 177 | Label { |
| 178 | Text(destination.title) |
| 179 | } icon: { |
| 180 | if let symbol = UIImage(systemName: destination.icon) { |
| 181 | let color = navigationIconColor(for: destination, palette: palette) |
| 182 | Image(uiImage: symbol.withTintColor(UIColor(color), renderingMode: .alwaysOriginal)) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | private struct MobileLibraryLoadingView: View { |
| 189 | @Environment(\.colorScheme) private var colorScheme |
| 190 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 191 | @State private var move = false |
| 192 | |
| 193 | var body: some View { |
| 194 | let ink = Color(white: colorScheme == .dark ? 0.73 : 0.36) |
| 195 | ZStack { |
| 196 | Color(white: colorScheme == .dark ? 0.12 : 0.95).ignoresSafeArea() |
| 197 | VStack(spacing: 16) { |
| 198 | Image("InkspringBrand").resizable().scaledToFit() |
| 199 | .frame(width: 44, height: 44).grayscale(1) |
| 200 | Capsule().fill(ink.opacity(0.2)) |
| 201 | .frame(width: 112, height: 3) |
| 202 | .overlay(alignment: .leading) { |
| 203 | Capsule().fill(ink).frame(width: 32, height: 3) |
| 204 | .offset(x: reduceMotion ? 40 : (move ? 80 : 0)) |
| 205 | } |
| 206 | Text("Checking your iCloud library…").font(.footnote).foregroundStyle(ink) |
| 207 | } |
| 208 | .accessibilityElement(children: .ignore) |
| 209 | .accessibilityLabel("Checking your iCloud library") |
| 210 | .accessibilityIdentifier("library.initialLoad") |
| 211 | } |
| 212 | .task(id: reduceMotion) { |
| 213 | if !reduceMotion { |
| 214 | withAnimation(.easeInOut(duration: 1.6).repeatForever(autoreverses: true)) { move = true } |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | private struct MobileWelcomeView: View { |
| 221 | @Environment(\.studioPalette) private var palette |
| 222 | let connected: Bool |
| 223 | let replay: Bool |
| 224 | let write: () -> Void |
| 225 | let enter: () -> Void |
| 226 | |
| 227 | var body: some View { |
| 228 | ScrollView { |
| 229 | VStack(alignment: .leading, spacing: 22) { |
| 230 | VStack(alignment: .leading, spacing: 12) { |
| 231 | Image("InkspringBrand").resizable().scaledToFit().frame(width: 64, height: 64) |
| 232 | .clipShape(.rect(cornerRadius: 15)).shadow(color: .black.opacity(0.13), radius: 5, y: 2) |
| 233 | .accessibilityHidden(true) |
| 234 | Text("Welcome to Inkspring").font(.largeTitle.bold()).accessibilityAddTraits(.isHeader) |
| 235 | Text("Save an idea here as soon as it comes to you. Connect Inkspring on your Mac to edit posts and newsletters, work on scripts, and schedule posts on the go.") |
| 236 | .foregroundStyle(palette.muted) |
| 237 | } |
| 238 | VStack(alignment: .leading, spacing: 16) { |
| 239 | Label("Set up your Mac", systemImage: "desktopcomputer").font(.headline) |
| 240 | .accessibilityAddTraits(.isHeader) |
| 241 | Text("Open Inkspring on a Mac signed in to the same Apple Account as this device.") |
| 242 | Link("Get Inkspring for Mac ↗", destination: URL(string: "https://inkspring.ai/download")!) |
| 243 | .font(.subheadline.weight(.semibold)) |
| 244 | Divider() |
| 245 | Text("In Inkspring on your Mac, open **Settings** and choose **Storage & backups → iPhone and iPad**. Turn on **schedule sync**, then **library sync**.") |
| 246 | Text("Keep your Mac awake with Inkspring open for the first sync and when you want scheduled posts to go out.") |
| 247 | .font(.subheadline).foregroundStyle(palette.muted) |
| 248 | }.padding(20).frame(maxWidth: .infinity, alignment: .leading) |
| 249 | .background(palette.card, in: .rect(cornerRadius: 18)) |
| 250 | .overlay { RoundedRectangle(cornerRadius: 18).strokeBorder(palette.line) } |
| 251 | VStack(spacing: 8) { |
| 252 | Button(action: connected || replay ? enter : write) { |
| 253 | Text(replay ? "Done" : connected ? "Open my workspace" : "Write my first idea") |
| 254 | .font(.headline).foregroundStyle(palette.accentText).frame(maxWidth: .infinity).padding(.vertical, 6) |
| 255 | }.buttonStyle(.borderedProminent).controlSize(.large).buttonBorderShape(.capsule) |
| 256 | .accessibilityIdentifier("welcome.primary") |
| 257 | if !replay { |
| 258 | Button(connected ? "Write an idea" : "Continue to workspace", action: connected ? write : enter) |
| 259 | .font(.subheadline.weight(.semibold)).frame(minHeight: 44) |
| 260 | } |
| 261 | } |
| 262 | }.foregroundStyle(palette.text).frame(maxWidth: 500).padding(24) |
| 263 | .frame(maxWidth: .infinity) |
| 264 | }.background(palette.canvas.ignoresSafeArea()) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | private struct CompanionScheduleView: View { |
| 269 | enum Destination: String { |
| 270 | case schedule = "Schedule" |
| 271 | case published = "Published" |
| 272 | |
| 273 | var icon: String { self == .published ? "paperplane" : "calendar.badge.clock" } |
| 274 | var syncHelp: String { |
| 275 | if self == .published { |
| 276 | return "Turn on schedule sync in Inkspring on your Mac to see what went out. Use the same Apple Account on both devices." |
| 277 | } |
| 278 | return "Turn on schedule sync in Inkspring on your Mac. Use the same Apple Account on both devices." |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | let library: MobileLibrary |
| 283 | let schedule: MobileSchedule |
| 284 | let destination: Destination |
| 285 | @Environment(\.mobileWideLayout) private var wideLayout |
| 286 | @Environment(\.studioPalette) private var palette |
| 287 | @State private var candidate: CompanionPost? |
| 288 | @State private var message: String? |
| 289 | private var state: CompanionScheduleViewState { schedule.state } |
| 290 | |
| 291 | var body: some View { |
| 292 | NavigationStack { |
| 293 | Group { |
| 294 | if destination == .published, let snapshot = state.schedule { |
| 295 | publishedFeed(snapshot) |
| 296 | } else if destination == .schedule, state.schedule != nil || !library.pendingSchedules.isEmpty { |
| 297 | let days = Dictionary(grouping: (state.schedule?.posts ?? []).sorted { $0.scheduledAt < $1.scheduledAt }) { |
| 298 | Calendar.current.startOfDay(for: $0.scheduledAt) |
| 299 | } |
| 300 | List { |
| 301 | if state.error != nil, state.schedule != nil { |
| 302 | Section { |
| 303 | Label("Showing the last synced schedule. Cancellation is available when iCloud reconnects.", |
| 304 | systemImage: "exclamationmark.icloud").foregroundStyle(.secondary) |
| 305 | .listRowBackground(palette.card) |
| 306 | } |
| 307 | } |
| 308 | if !library.pendingSchedules.isEmpty { |
| 309 | Section("Scheduling requests") { |
| 310 | ForEach(library.pendingSchedules) { request in |
| 311 | VStack(alignment: .leading, spacing: 6) { |
| 312 | Text(request.item.title).font(.headline) |
| 313 | Text("Requested for \(mobileDateAndTime(request.hour))") |
| 314 | .lineLimit(nil).fixedSize(horizontal: false, vertical: true) |
| 315 | Label(request.error ?? "Waiting for your Mac", |
| 316 | systemImage: request.error == nil ? "clock" : "exclamationmark.icloud") |
| 317 | MobilePostImage(data: request.item.imagePreview, label: "Post image", |
| 318 | identifier: "schedule.image." + request.item.id) |
| 319 | MobileLastUpdated(date: request.requestedAt) |
| 320 | } |
| 321 | .font(.subheadline) |
| 322 | .listRowBackground(palette.card) |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | if days.isEmpty, library.pendingSchedules.isEmpty { |
| 327 | ContentUnavailableView("Nothing scheduled", systemImage: "calendar", |
| 328 | description: Text("Open a draft in Review to choose a posting day and hour.")) |
| 329 | .listRowBackground(Color.clear) |
| 330 | } else { |
| 331 | ForEach(days.keys.sorted(), id: \.self) { day in |
| 332 | Section { |
| 333 | ForEach(days[day] ?? []) { post in |
| 334 | row(post, workspaceID: state.schedule?.workspaceID).listRowBackground(palette.card) |
| 335 | } |
| 336 | } header: { |
| 337 | Text(day, format: .dateTime.weekday(.wide).month(.abbreviated).day()) |
| 338 | } |
| 339 | } |
| 340 | if let schedule = state.schedule { |
| 341 | Text("Synced from your Mac \(schedule.updatedAt.formatted(.relative(presentation: .named))).") |
| 342 | .font(.footnote).foregroundStyle(.secondary).listRowBackground(Color.clear) |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | .listStyle(.insetGrouped) |
| 347 | .scrollContentBackground(.hidden) |
| 348 | } else if state.loading { |
| 349 | ProgressView("Checking iCloud…").frame(maxHeight: .infinity) |
| 350 | } else { |
| 351 | ContentUnavailableView { |
| 352 | Label("\(destination.rawValue) unavailable", systemImage: destination.icon) |
| 353 | } description: { |
| 354 | Text(state.error ?? destination.syncHelp) |
| 355 | } actions: { |
| 356 | Button("Check again") { Task { await schedule.refresh() } }.buttonStyle(.bordered) |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | .frame(maxWidth: 760) |
| 361 | .mobileCanvas() |
| 362 | .navigationTitle(destination.rawValue) |
| 363 | .navigationBarTitleDisplayMode(wideLayout ? .inline : .automatic) |
| 364 | .toolbar(wideLayout ? .hidden : .visible, for: .tabBar) |
| 365 | .refreshable { await schedule.refresh() } |
| 366 | .toolbar { |
| 367 | ToolbarItem(placement: .topBarTrailing) { |
| 368 | Button("Refresh", systemImage: "arrow.clockwise") { Task { await schedule.refresh() } } |
| 369 | .disabled(state.busy) |
| 370 | } |
| 371 | } |
| 372 | .confirmationDialog("Cancel this scheduled post?", isPresented: Binding( |
| 373 | get: { candidate != nil }, set: { if !$0 { candidate = nil } } |
| 374 | ), titleVisibility: .visible, presenting: candidate) { post in |
| 375 | Button("Cancel scheduled post", role: .destructive) { |
| 376 | Task { message = await schedule.cancel(post) } |
| 377 | } |
| 378 | Button("Keep post", role: .cancel) {} |
| 379 | } message: { post in |
| 380 | Text("“\(post.title)” stays in Inkspring on your Mac so you can edit or schedule it again.") |
| 381 | } |
| 382 | .alert("Inkspring", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { |
| 383 | Button("OK", role: .cancel) { message = nil } |
| 384 | } message: { |
| 385 | Text(message ?? "") |
| 386 | } |
| 387 | } |
| 388 | .onChange(of: state.account) { _, _ in |
| 389 | candidate = nil |
| 390 | message = nil |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | private func publishedFeed(_ schedule: CompanionSchedule) -> some View { |
| 395 | List { |
| 396 | if state.error != nil { |
| 397 | Label("Showing the last synced posts.", systemImage: "exclamationmark.icloud") |
| 398 | .foregroundStyle(.secondary).listRowBackground(palette.card) |
| 399 | } |
| 400 | if let published = schedule.published, !published.isEmpty { |
| 401 | ForEach(published) { post in |
| 402 | VStack(alignment: .leading, spacing: 7) { |
| 403 | StudioPlatformLabel(name: post.channel, title: post.channelName) |
| 404 | .font(.subheadline.weight(.semibold)) |
| 405 | Text(post.title).font(.headline) |
| 406 | MobilePostImage(data: library.imagePreview(post.id, in: schedule.workspaceID), |
| 407 | label: "Published image", identifier: "published.image." + post.id) |
| 408 | Text(post.project).font(.subheadline).foregroundStyle(.secondary) |
| 409 | Text("Published \(mobileDateAndTime(post.publishedAt))") |
| 410 | .font(.subheadline).foregroundStyle(.secondary) |
| 411 | .lineLimit(nil).fixedSize(horizontal: false, vertical: true) |
| 412 | MobileLastUpdated(date: library.lastUpdated(post.id, in: schedule.workspaceID) ?? post.lastUpdatedAt) |
| 413 | if post.incomplete { Text("Partially published").font(.caption).foregroundStyle(.secondary) } |
| 414 | ForEach(Array(post.links.enumerated()), id: \.offset) { index, link in |
| 415 | Link(destination: link) { |
| 416 | Label(index == 0 ? "Open on \(post.channelName)" : "Open follow-up \(index)", |
| 417 | systemImage: "arrow.up.right") |
| 418 | } |
| 419 | .buttonStyle(.bordered) |
| 420 | .accessibilityIdentifier("published.open.\(post.id).\(index)") |
| 421 | } |
| 422 | if post.links.isEmpty { Text("No post link saved").font(.caption).foregroundStyle(.secondary) } |
| 423 | } |
| 424 | .padding(.vertical, 6) |
| 425 | .listRowBackground(palette.card) |
| 426 | } |
| 427 | } else { |
| 428 | ContentUnavailableView("No published posts", systemImage: "paperplane", |
| 429 | description: Text(schedule.published == nil |
| 430 | ? "Update Inkspring on your Mac and sync to see your published posts." |
| 431 | : "Posts appear here after Inkspring confirms that they went out.")) |
| 432 | .listRowBackground(Color.clear) |
| 433 | } |
| 434 | if schedule.hasOlderPublications == true { |
| 435 | Text("Older posts are available in Published on your Mac.") |
| 436 | .font(.footnote).foregroundStyle(.secondary).listRowBackground(Color.clear) |
| 437 | } |
| 438 | } |
| 439 | .listStyle(.insetGrouped) |
| 440 | .scrollContentBackground(.hidden) |
| 441 | } |
| 442 | |
| 443 | private func row(_ post: CompanionPost, workspaceID: UUID?) -> some View { |
| 444 | VStack(alignment: .leading, spacing: 7) { |
| 445 | HStack { |
| 446 | StudioPlatformLabel(name: post.channel, title: post.channel).font(.subheadline.weight(.semibold)) |
| 447 | Spacer() |
| 448 | if post.state != .queued { |
| 449 | Text(stateLabel(post.state)).font(.caption).foregroundStyle(.secondary) |
| 450 | } |
| 451 | } |
| 452 | Text(post.title).font(.headline) |
| 453 | MobilePostImage(data: workspaceID.flatMap { library.imagePreview(post.id, in: $0) }, |
| 454 | label: "Scheduled image", identifier: "schedule.image." + post.id) |
| 455 | Text(post.project).font(.subheadline).foregroundStyle(.secondary) |
| 456 | Text("Scheduled for \(mobileDateAndTime(post.scheduledAt))") |
| 457 | .font(.subheadline).foregroundStyle(.secondary) |
| 458 | .lineLimit(nil).fixedSize(horizontal: false, vertical: true) |
| 459 | MobileLastUpdated(date: workspaceID.flatMap { library.lastUpdated(post.id, in: $0) } ?? post.lastUpdatedAt) |
| 460 | if post.canCancel && [.queued, .review].contains(post.state) { |
| 461 | Button("Cancel schedule", role: .destructive) { candidate = post } |
| 462 | .buttonStyle(.bordered) |
| 463 | .disabled(!state.canCancel) |
| 464 | .padding(.top, 3) |
| 465 | } |
| 466 | } |
| 467 | .padding(.vertical, 6) |
| 468 | } |
| 469 | |
| 470 | private func stateLabel(_ state: CompanionPost.State) -> String { |
| 471 | switch state { |
| 472 | case .queued: "Scheduled" |
| 473 | case .review: "Needs review" |
| 474 | case .cancelled: "Cancelled" |
| 475 | case .sending: "Sending" |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | } |
| 480 | |
| 481 | func mobileTimestamp(_ value: String) -> Date? { |
| 482 | (try? Date(value, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true))) |
| 483 | ?? (try? Date(value, strategy: .iso8601)) |
| 484 | } |
| 485 | |
| 486 | func mobileDateAndTime(_ date: Date) -> String { |
| 487 | date.formatted(date: .abbreviated, time: .shortened) |
| 488 | } |
| 489 | |
| 490 | struct MobileLastUpdated: View { |
| 491 | @Environment(\.studioPalette) private var palette |
| 492 | let date: Date? |
| 493 | |
| 494 | var body: some View { |
| 495 | if let date { |
| 496 | Text("Updated \(mobileDateAndTime(date))") |
| 497 | .font(.caption) |
| 498 | .foregroundStyle(palette.muted) |
| 499 | .lineLimit(nil) |
| 500 | .fixedSize(horizontal: false, vertical: true) |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | @MainActor |
| 506 | @Observable |
| 507 | private final class MobileSchedule { |
| 508 | private(set) var state = CompanionScheduleViewState() |
| 509 | private var cloudStore: CloudScheduleStore? |
| 510 | |
| 511 | func accountChanged() { |
| 512 | state = CompanionScheduleViewState() |
| 513 | } |
| 514 | |
| 515 | func refresh() async { |
| 516 | guard let token = state.begin(.refresh) else { return } |
| 517 | do { |
| 518 | #if DEBUG |
| 519 | if ProcessInfo.processInfo.arguments.contains("--schedule-fixture") { |
| 520 | if state.schedule != nil, ProcessInfo.processInfo.arguments.contains("--schedule-offline-fixture") { |
| 521 | throw CompanionScheduleError.cloudTemporarilyUnavailable |
| 522 | } |
| 523 | let snapshot = state.schedule ?? Self.fixture |
| 524 | guard state.confirmAccount("fixture", for: token) else { return } |
| 525 | state.complete(snapshot, for: token) |
| 526 | return |
| 527 | } |
| 528 | #endif |
| 529 | let store = cloud() |
| 530 | let account = try await store.accountKey() |
| 531 | guard state.confirmAccount(account, for: token) else { return } |
| 532 | let snapshot = try await store.load(confirmedAccount: account) |
| 533 | state.complete(snapshot, for: token) |
| 534 | } catch { |
| 535 | state.fail(error.localizedDescription, keepSchedule: temporary(error), for: token) |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | func cancel(_ post: CompanionPost) async -> String? { |
| 540 | guard let schedule = state.schedule, let account = state.account, |
| 541 | let token = state.begin(.cancel) else { return nil } |
| 542 | do { |
| 543 | #if DEBUG |
| 544 | if ProcessInfo.processInfo.arguments.contains("--schedule-fixture") { |
| 545 | var fixture = schedule |
| 546 | try fixture.cancel(post) |
| 547 | state.complete(fixture, for: token) |
| 548 | return nil |
| 549 | } |
| 550 | #endif |
| 551 | let updated = try await cloud().update(workspaceID: schedule.workspaceID, expectedAccount: account) { try $0.cancel(post) } |
| 552 | state.complete(updated, for: token) |
| 553 | return nil |
| 554 | } catch { |
| 555 | guard state.isCurrent(token) else { return nil } |
| 556 | let message = error.localizedDescription |
| 557 | state.fail(message, keepSchedule: temporary(error), for: token) |
| 558 | await refresh() |
| 559 | return message |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | private func cloud() -> CloudScheduleStore { |
| 564 | if let cloudStore { return cloudStore } |
| 565 | let store = CloudScheduleStore() |
| 566 | cloudStore = store |
| 567 | return store |
| 568 | } |
| 569 | |
| 570 | private func temporary(_ error: Error) -> Bool { |
| 571 | if (error as? CompanionScheduleError) == .cloudTemporarilyUnavailable { return true } |
| 572 | guard let cloudError = error as? CKError else { return false } |
| 573 | return [.networkUnavailable, .networkFailure, .serviceUnavailable, .requestRateLimited, |
| 574 | .zoneBusy, .accountTemporarilyUnavailable].contains(cloudError.code) |
| 575 | } |
| 576 | |
| 577 | #if DEBUG |
| 578 | private static let fixture = CompanionSchedule(workspaceID: |
| 579 | ProcessInfo.processInfo.environment["INKSPRING_FIXTURE_ID"].flatMap(UUID.init(uuidString:)) ?? UUID(), posts: [ |
| 580 | CompanionPost(id: "fixture-1", revision: "1", title: "A quieter way to draft", project: "Studio", |
| 581 | channel: "LinkedIn", scheduledAt: .now.addingTimeInterval(10_800), state: .queued, canCancel: true, |
| 582 | lastUpdatedAt: .now.addingTimeInterval(-14_400)), |
| 583 | CompanionPost(id: "fixture-2", revision: "1", title: "This month’s studio notes", project: "Studio", |
| 584 | channel: "Substack", scheduledAt: .now.addingTimeInterval(91_000), state: .queued, canCancel: false) |
| 585 | ], published: [ |
| 586 | CompanionPublication(id: "fixture-published", title: "A quieter way to publish", project: "Studio", |
| 587 | channel: "substack", publishedAt: .now.addingTimeInterval(-3_600), |
| 588 | links: [URL(string: "https://newsletter.protomota.com/")!], |
| 589 | lastUpdatedAt: .now.addingTimeInterval(-1_800)) |
| 590 | ]) |
| 591 | #endif |
| 592 | } |
| 593 | |
| 594 | private struct MobileWideLayoutKey: EnvironmentKey { |
| 595 | static let defaultValue = false |
| 596 | } |
| 597 | |
| 598 | extension EnvironmentValues { |
| 599 | var mobileWideLayout: Bool { |
| 600 | get { self[MobileWideLayoutKey.self] } |
| 601 | set { self[MobileWideLayoutKey.self] = newValue } |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | extension View { |
| 606 | func mobilePageTitle(_ title: String, wide: Bool, background: Color) -> some View { |
| 607 | self |
| 608 | .safeAreaInset(edge: .top, spacing: 0) { |
| 609 | if wide { |
| 610 | Text(title) |
| 611 | .font(.largeTitle.bold()) |
| 612 | .accessibilityAddTraits(.isHeader) |
| 613 | .padding(.horizontal, 24) |
| 614 | .padding(.vertical, 12) |
| 615 | .frame(maxWidth: .infinity, alignment: .leading) |
| 616 | .background(background.ignoresSafeArea(edges: .top)) |
| 617 | } |
| 618 | } |
| 619 | .navigationTitle(title) |
| 620 | .toolbar(wide ? .hidden : .automatic, for: .navigationBar) |
| 621 | } |
| 622 | } |