Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / SubstackViews.swift
| 1 | import SwiftUI |
| 2 | import WebKit |
| 3 | |
| 4 | struct SubstackConnectionSettings: View { |
| 5 | @Environment(\.studioPalette) private var palette |
| 6 | let workspace: Workspace |
| 7 | @State private var signingIn = false |
| 8 | @State private var disconnecting = false |
| 9 | @State private var connection: Connection = .unchecked |
| 10 | @State private var checkRequest = 0 |
| 11 | |
| 12 | private enum Connection { |
| 13 | case unchecked, checking, connected(Date), failed(String) |
| 14 | } |
| 15 | |
| 16 | private var service: Substack { Substack(workspace: workspace) } |
| 17 | |
| 18 | var body: some View { |
| 19 | GroupBox("Substack") { |
| 20 | VStack(alignment: .leading, spacing: 12) { |
| 21 | Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 12) { |
| 22 | GridRow { |
| 23 | connectionStatus |
| 24 | .frame(maxWidth: .infinity, alignment: .leading) |
| 25 | connectionActions |
| 26 | .gridColumnAlignment(.trailing) |
| 27 | } |
| 28 | GridRow { |
| 29 | publicationPicker |
| 30 | SetupHelpLink("Substack setup and troubleshooting", topic: "substack") |
| 31 | } |
| 32 | } |
| 33 | if case let .failed(message) = connection { |
| 34 | Text(message).font(.callout).foregroundStyle(palette.danger) |
| 35 | } |
| 36 | } |
| 37 | .frame(maxWidth: .infinity, alignment: .leading) |
| 38 | .disabled(workspace.substackBusy) |
| 39 | } |
| 40 | .task(id: checkRequest) { await verifyConnection() } |
| 41 | .onChange(of: service.selected?.id) { checkRequest += 1 } |
| 42 | .sheet(isPresented: $signingIn) { |
| 43 | SubstackSignIn(workspace: workspace) { connection = .connected(.now) } |
| 44 | } |
| 45 | .confirmationDialog("Disconnect Substack?", isPresented: $disconnecting) { |
| 46 | Button("Disconnect", role: .destructive) { |
| 47 | Task { |
| 48 | do { |
| 49 | try await service.disconnect() |
| 50 | connection = .unchecked |
| 51 | } |
| 52 | catch { workspace.error = error.localizedDescription } |
| 53 | } |
| 54 | } |
| 55 | } message: { |
| 56 | Text("This clears the Inkspring sign-in on this Mac. Your saved newsletters and their Substack links are kept.") |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | private var publicationPicker: some View { |
| 61 | HStack(spacing: 10) { |
| 62 | if !service.publications.isEmpty { |
| 63 | Text("Publication").foregroundStyle(palette.muted) |
| 64 | StudioChoicePicker(title: "Publication", selection: Binding(get: { service.selected?.id ?? "" }, set: { id in |
| 65 | workspace.perform { try service.select(id) } |
| 66 | }), options: service.publications.map(\.id), |
| 67 | label: { id in service.publications.first(where: { $0.id == id })?.name ?? "Choose a publication" }) |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | private var connectionActions: some View { |
| 73 | HStack(spacing: 8) { |
| 74 | if !service.accountName.isEmpty { |
| 75 | Button("Test connection") { checkRequest += 1 } |
| 76 | .disabled(isChecking) |
| 77 | } |
| 78 | Button(service.accountName.isEmpty ? "Sign in…" : "Sign in again…") { signingIn = true } |
| 79 | if !service.accountName.isEmpty { Button("Disconnect…") { disconnecting = true } } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | private var isChecking: Bool { |
| 84 | if case .checking = connection { return true } |
| 85 | return false |
| 86 | } |
| 87 | |
| 88 | @ViewBuilder private var connectionStatus: some View { |
| 89 | if service.accountName.isEmpty { |
| 90 | Label("Not connected", systemImage: "minus.circle").foregroundStyle(palette.muted) |
| 91 | } else { |
| 92 | switch connection { |
| 93 | case .unchecked: |
| 94 | Text("Connection not verified").foregroundStyle(palette.muted) |
| 95 | case .checking: |
| 96 | ProgressView("Checking connection…").controlSize(.small) |
| 97 | case .connected(let checkedAt): |
| 98 | VStack(alignment: .leading, spacing: 4) { |
| 99 | Label("Connected as \(service.accountName)", systemImage: "checkmark.circle.fill") |
| 100 | .foregroundStyle(palette.success) |
| 101 | Text("Verified at \(checkedAt.formatted(date: .omitted, time: .shortened))") |
| 102 | .font(.caption).foregroundStyle(palette.muted) |
| 103 | } |
| 104 | case .failed: |
| 105 | Label("Connection needs attention", systemImage: "exclamationmark.circle").foregroundStyle(palette.danger) |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | private func verifyConnection() async { |
| 111 | guard !service.accountName.isEmpty else { |
| 112 | connection = .unchecked |
| 113 | return |
| 114 | } |
| 115 | connection = .checking |
| 116 | do { |
| 117 | try await service.checkConnection() |
| 118 | if !Task.isCancelled { connection = .connected(.now) } |
| 119 | } catch { |
| 120 | if !Task.isCancelled { connection = .failed(error.localizedDescription) } |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | private struct SubstackSignIn: View { |
| 126 | @Environment(\.studioPalette) private var palette |
| 127 | let workspace: Workspace |
| 128 | let connected: () -> Void |
| 129 | @Environment(\.dismiss) private var dismiss |
| 130 | @State private var message: String? |
| 131 | |
| 132 | var body: some View { |
| 133 | VStack(alignment: .leading, spacing: 12) { |
| 134 | PageHeading(title: "Sign in to Substack") |
| 135 | SubstackLoginPage(storage: workspace.substackSession.storage) { message = $0 } |
| 136 | if let message { Text(message).foregroundStyle(.red).textSelection(.enabled) } |
| 137 | HStack { |
| 138 | Button("Close", role: .cancel) { dismiss() } |
| 139 | Spacer() |
| 140 | if workspace.substackBusy { ProgressView().controlSize(.small) } |
| 141 | Button("Check connection") { |
| 142 | Task { |
| 143 | do { |
| 144 | try await Substack(workspace: workspace).connect() |
| 145 | connected() |
| 146 | dismiss() |
| 147 | } catch { message = error.localizedDescription } |
| 148 | } |
| 149 | } |
| 150 | .disabled(workspace.substackBusy) |
| 151 | } |
| 152 | } |
| 153 | .padding(20) |
| 154 | .frame(width: 660, height: 680) |
| 155 | .studioAppearance(palette) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | private struct SubstackLoginPage: NSViewRepresentable { |
| 160 | let storage: WKWebsiteDataStore |
| 161 | let report: (String) -> Void |
| 162 | |
| 163 | func makeCoordinator() -> Coordinator { Coordinator(report: report) } |
| 164 | |
| 165 | func makeNSView(context: Context) -> WKWebView { |
| 166 | let configuration = WKWebViewConfiguration() |
| 167 | configuration.websiteDataStore = storage |
| 168 | let view = WKWebView(frame: .zero, configuration: configuration) |
| 169 | view.navigationDelegate = context.coordinator |
| 170 | view.uiDelegate = context.coordinator |
| 171 | view.load(URLRequest(url: URL(string: "https://substack.com/sign-in")!)) |
| 172 | return view |
| 173 | } |
| 174 | |
| 175 | func updateNSView(_ view: WKWebView, context: Context) {} |
| 176 | |
| 177 | final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate { |
| 178 | let report: (String) -> Void |
| 179 | |
| 180 | init(report: @escaping (String) -> Void) { |
| 181 | self.report = report |
| 182 | } |
| 183 | |
| 184 | func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy { |
| 185 | action.request.url.map(SubstackSession.loginAddress) == true ? .allow : .cancel |
| 186 | } |
| 187 | |
| 188 | func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, |
| 189 | for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { |
| 190 | if navigationAction.request.url.map(SubstackSession.loginAddress) == true { webView.load(navigationAction.request) } |
| 191 | return nil |
| 192 | } |
| 193 | |
| 194 | func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: any Error) { |
| 195 | guard (error as NSError).code != NSURLErrorCancelled else { return } |
| 196 | report("Substack sign-in couldn’t load. Check your connection and reopen sign-in.") |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | struct NewsletterSubstackControls: View { |
| 202 | let workspace: Workspace |
| 203 | let record: WorkspaceRecord |
| 204 | let hasEdits: Bool |
| 205 | let updated: (WorkspaceRecord) -> Void |
| 206 | let report: (String?) -> Void |
| 207 | |
| 208 | let reviewSend: (Bool) -> Void |
| 209 | |
| 210 | @State private var cancelling = false |
| 211 | @State private var acknowledging = false |
| 212 | |
| 213 | private var service: Substack { Substack(workspace: workspace) } |
| 214 | private var state: String { record["state"] } |
| 215 | |
| 216 | var body: some View { |
| 217 | GroupBox("Substack") { |
| 218 | VStack(alignment: .leading, spacing: 10) { |
| 219 | HStack { |
| 220 | Text(state == "uncertain" ? "Check the last attempt" : state.capitalized) |
| 221 | if let date = record["scheduledAt"].isEmpty ? nil : try? Date(record["scheduledAt"], strategy: .iso8601) { |
| 222 | Text(date, format: .dateTime.month(.abbreviated).day().hour().minute()).foregroundStyle(.secondary) |
| 223 | } |
| 224 | Spacer() |
| 225 | if workspace.substackBusy { ProgressView().controlSize(.small) } |
| 226 | if let url = Substack.editorURL(record) { StudioExternalLink("Open in Substack", destination: url) } |
| 227 | } |
| 228 | if !record["error"].isEmpty { Text(record["error"]).font(.callout).foregroundStyle(.secondary) } |
| 229 | if let publication = service.selected { |
| 230 | Text(publication.name).font(.caption).foregroundStyle(.secondary) |
| 231 | } else { |
| 232 | Text("Choose a publication in Settings → Connections.").font(.caption).foregroundStyle(.secondary) |
| 233 | } |
| 234 | HStack { |
| 235 | if ["draft", "synced"].contains(state) { |
| 236 | Button("Save to Substack") { run { try await service.sync(record.id) } } |
| 237 | .disabled(hasEdits || service.selected == nil || record["body"].isEmpty) |
| 238 | } |
| 239 | if !record["remoteId"].isEmpty { |
| 240 | Button("Check status") { run { try await service.refresh(record.id) } } |
| 241 | .disabled(hasEdits || service.selected == nil) |
| 242 | } |
| 243 | if state == "synced" { |
| 244 | Button("Review & publish…") { reviewSend(false) } |
| 245 | .disabled(hasEdits) |
| 246 | Button("Choose a time…") { reviewSend(true) } |
| 247 | .disabled(hasEdits) |
| 248 | } |
| 249 | if state == "scheduled" { |
| 250 | Button("Cancel schedule…") { cancelling = true } |
| 251 | .disabled(service.selected == nil) |
| 252 | } |
| 253 | if state == "uncertain" { |
| 254 | Button("Confirm Substack check…") { acknowledging = true } |
| 255 | } |
| 256 | } |
| 257 | .disabled(workspace.substackBusy) |
| 258 | if hasEdits { Text("Save your local changes before continuing.").font(.caption).foregroundStyle(.secondary) } |
| 259 | } |
| 260 | .frame(maxWidth: .infinity, alignment: .leading) |
| 261 | } |
| 262 | .confirmationDialog("Cancel the send in Substack?", isPresented: $cancelling) { |
| 263 | Button("Cancel schedule", role: .destructive) { run { try await service.cancel(record.id) } } |
| 264 | } |
| 265 | .confirmationDialog("Did you check the outcome in Substack?", isPresented: $acknowledging) { |
| 266 | Button("I checked Substack") { run { try await service.acknowledge(record.id) } } |
| 267 | } message: { |
| 268 | Text("Check your drafts, scheduled posts, and published posts before continuing.") |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | private func run(_ operation: @escaping @MainActor () async throws -> WorkspaceRecord) { |
| 273 | report(nil) |
| 274 | Task { |
| 275 | do { updated(try await operation()) } |
| 276 | catch { |
| 277 | if let latest = workspace.records.first(where: { $0.id == record.id }) { updated(latest) } |
| 278 | report(error.localizedDescription) |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | struct NewsletterSendPage: View { |
| 285 | @Environment(\.studioPalette) private var palette |
| 286 | let record: WorkspaceRecord |
| 287 | let workspace: Workspace |
| 288 | let scheduling: Bool |
| 289 | let close: () -> Void |
| 290 | let completed: (WorkspaceRecord) -> Void |
| 291 | @State private var date = Date.now.addingTimeInterval(3600) |
| 292 | @State private var review: SubstackReview? |
| 293 | @State private var working = false |
| 294 | @State private var confirmingCancellation = false |
| 295 | @State private var message: String? |
| 296 | |
| 297 | private var service: Substack { Substack(workspace: workspace) } |
| 298 | private var item: WorkspaceRecord? { workspace.records.first { $0.id == record.id && $0.kind == "newsletter" } } |
| 299 | private var isScheduled: Bool { item?["state"] == "scheduled" } |
| 300 | private var busy: Bool { working || workspace.substackBusy } |
| 301 | private var canSend: Bool { item.map { ["draft", "synced"].contains($0["state"]) } ?? false } |
| 302 | private var hasText: Bool { item.map { !$0.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? false } |
| 303 | private var needsSync: Bool { |
| 304 | guard let item else { return false } |
| 305 | return Substack.needsSync(item) |
| 306 | } |
| 307 | |
| 308 | var body: some View { |
| 309 | StudioEditorPage(title: scheduling ? "Choose a newsletter time" : "Review newsletter send") { |
| 310 | Button("Back", systemImage: "chevron.left", action: close) |
| 311 | .keyboardShortcut(.cancelAction) |
| 312 | .disabled(busy) |
| 313 | if busy { ProgressView().controlSize(.small) } |
| 314 | if let review { |
| 315 | Button(review.scheduledAt == nil ? "Publish newsletter" : "Schedule newsletter") { |
| 316 | self.review = nil |
| 317 | run { |
| 318 | let result = try await service.commit(review) |
| 319 | workspace.showPostResult(result) |
| 320 | completed(result) |
| 321 | close() |
| 322 | } |
| 323 | } |
| 324 | .modifier(PrimaryActionStyle()) |
| 325 | .disabled(busy) |
| 326 | } else if canSend, service.selected != nil { |
| 327 | if needsSync { |
| 328 | Button("Save to Substack") { run { _ = try await service.sync(record.id) } } |
| 329 | .modifier(PrimaryActionStyle()) |
| 330 | .disabled(!hasText || busy) |
| 331 | } else { |
| 332 | Button(scheduling ? "Review schedule" : "Review newsletter") { prepare() } |
| 333 | .modifier(PrimaryActionStyle()) |
| 334 | .disabled(busy) |
| 335 | } |
| 336 | } |
| 337 | } content: { |
| 338 | StudioScrollView { |
| 339 | VStack(alignment: .leading, spacing: 16) { |
| 340 | Text(item?.title ?? record.title).font(InkspringTypography.editorial(24)) |
| 341 | if let review { |
| 342 | LabeledContent("Publication", value: review.publication.name) |
| 343 | LabeledContent("Audience", value: Substack.audienceLabel(review.audience)) |
| 344 | LabeledContent("Email subscribers", value: review.sendEmail ? "Yes" : "No") |
| 345 | if let scheduled = review.scheduledAt { |
| 346 | LabeledContent("Scheduled", value: scheduled.formatted(date: .long, time: .shortened)) |
| 347 | } |
| 348 | Button(scheduling ? "Change time" : "Back to details") { self.review = nil } |
| 349 | } else { |
| 350 | if let publication = service.selected { |
| 351 | LabeledContent("Publication", value: publication.name) |
| 352 | } else { |
| 353 | Text("Connect Substack and choose a publication in Settings → Connections.") |
| 354 | .foregroundStyle(palette.muted) |
| 355 | } |
| 356 | if scheduling { |
| 357 | StudioDateTimePicker(selection: $date, includesFiveMinuteShortcut: true) |
| 358 | .disabled(busy || isScheduled) |
| 359 | } |
| 360 | if isScheduled { |
| 361 | Text("Cancel the current schedule before choosing a different time.") |
| 362 | .foregroundStyle(palette.muted) |
| 363 | Button("Cancel current schedule…", role: .destructive) { confirmingCancellation = true } |
| 364 | .disabled(busy || service.selected == nil) |
| 365 | } else if !canSend { |
| 366 | Text("Check the newsletter’s status in Substack before continuing.") |
| 367 | .foregroundStyle(palette.muted) |
| 368 | } else if !hasText { |
| 369 | Text("Add newsletter text before sending.").foregroundStyle(palette.muted) |
| 370 | } else if needsSync, service.selected != nil { |
| 371 | Text("Save the draft to Substack before reviewing the send.") |
| 372 | .foregroundStyle(palette.muted) |
| 373 | } |
| 374 | } |
| 375 | if let message { Text(message).foregroundStyle(palette.danger).textSelection(.enabled) } |
| 376 | } |
| 377 | .frame(maxWidth: 760, alignment: .leading) |
| 378 | .studioPage() |
| 379 | } |
| 380 | } |
| 381 | .onAppear { |
| 382 | if let date = scheduleDate(record["scheduledAt"]) { self.date = date } |
| 383 | } |
| 384 | .confirmationDialog("Cancel the current newsletter schedule?", isPresented: $confirmingCancellation) { |
| 385 | Button("Cancel schedule", role: .destructive) { run { _ = try await service.cancel(record.id) } } |
| 386 | } message: { |
| 387 | Text("The newsletter stays saved as a draft on Substack. Choose and confirm a new time to reschedule it.") |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | private func prepare() { |
| 392 | let minute = PostScheduling.startOfMinute(date) |
| 393 | run { review = try await service.prepare(record.id, at: scheduling ? minute : nil) } |
| 394 | } |
| 395 | |
| 396 | private func run(_ operation: @escaping @MainActor () async throws -> Void) { |
| 397 | guard !busy else { return } |
| 398 | working = true |
| 399 | message = nil |
| 400 | Task { |
| 401 | defer { working = false } |
| 402 | do { try await operation() } |
| 403 | catch { message = error.localizedDescription } |
| 404 | } |
| 405 | } |
| 406 | } |