Inkspring / app · inkspring.ai / native-mac / iPhone / MobileLibrary.swift
| 1 | import CloudKit |
| 2 | import CryptoKit |
| 3 | import FoundationModels |
| 4 | import SwiftUI |
| 5 | import UniformTypeIdentifiers |
| 6 | |
| 7 | private extension CompanionLibrary.Item { |
| 8 | var revisionDate: Date? { |
| 9 | mobileTimestamp(revision) |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | @MainActor @Observable |
| 14 | final class MobileLibrary { |
| 15 | private struct LibraryState { |
| 16 | var snapshot: CompanionLibrary? |
| 17 | var outbox = CompanionLibraryOutbox() |
| 18 | } |
| 19 | |
| 20 | private var state = LibraryState() |
| 21 | var snapshot: CompanionLibrary? { state.snapshot } |
| 22 | var error: String? |
| 23 | var busy = false |
| 24 | private(set) var lastCheck: Date? |
| 25 | private(set) var lastCloudContact: Date? |
| 26 | private(set) var accountStatus = "Not checked" |
| 27 | private(set) var remoteWorkspaceFound: Bool? |
| 28 | private(set) var syncErrorCode: String? |
| 29 | private var account: String? |
| 30 | private var accountRevision = UUID() |
| 31 | private var store: CloudScheduleStore? |
| 32 | private var syncedText: (workspace: UUID, version: CompanionLibrary.TextVersion, data: Data)? |
| 33 | static let preferences: UserDefaults = { |
| 34 | #if DEBUG |
| 35 | if ProcessInfo.processInfo.arguments.contains("--unpaired-fixture"), |
| 36 | let id = ProcessInfo.processInfo.environment["INKSPRING_FIXTURE_ID"], |
| 37 | let suite = UserDefaults(suiteName: "inkspring.onboarding.tests." + id) { return suite } |
| 38 | #endif |
| 39 | return .standard |
| 40 | }() |
| 41 | private let defaults = MobileLibrary.preferences |
| 42 | private static let outboxKey = "inkspring.mobile.libraryOutbox.v1" |
| 43 | private static let legacyIdeasKey = "inkspring.mobile.localIdeas.v1" |
| 44 | private var outbox: CompanionLibraryOutbox { state.outbox } |
| 45 | private var outboxLoaded = false |
| 46 | private var newsletterRefreshPending = false |
| 47 | #if DEBUG |
| 48 | private var staleFixtureSnapshot: CompanionLibrary? |
| 49 | #endif |
| 50 | |
| 51 | struct NewsletterEditRecovery: Codable { |
| 52 | let revision: String |
| 53 | let base: String |
| 54 | let markdown: String |
| 55 | var title: String? |
| 56 | var baseTitle: String? |
| 57 | } |
| 58 | |
| 59 | func planRecoveryID(_ itemID: String, workspaceID: UUID) -> String { |
| 60 | "\(account ?? "unavailable").\(workspaceID).\(itemID)" |
| 61 | } |
| 62 | |
| 63 | func newsletterRecoveryKey(for itemID: String, workspaceID: UUID) -> String? { |
| 64 | guard let account, snapshot?.workspaceID == workspaceID else { return nil } |
| 65 | return "inkspring.mobile.newsletterRecovery.\(account).\(workspaceID).\(itemID)" |
| 66 | } |
| 67 | |
| 68 | func recoverNewsletterEdit(key: String) -> NewsletterEditRecovery? { |
| 69 | guard let data = defaults.data(forKey: key) else { return nil } |
| 70 | return try? JSONDecoder().decode(NewsletterEditRecovery.self, from: data) |
| 71 | } |
| 72 | |
| 73 | func storeNewsletterRecovery(_ edit: NewsletterEditRecovery?, key: String) { |
| 74 | guard let edit else { |
| 75 | defaults.removeObject(forKey: key) |
| 76 | return |
| 77 | } |
| 78 | if let data = try? JSONEncoder().encode(edit) { |
| 79 | defaults.set(data, forKey: key) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | var pendingIdeas: [CompanionLibraryOutbox.Entry] { |
| 84 | outbox.entries.reversed().filter { |
| 85 | $0.action == .addIdea && $0.generatesXDraft != true && $0.createsScript != true && ($0.account == nil || $0.account == account) |
| 86 | && ($0.workspaceID == nil || $0.workspaceID == snapshot?.workspaceID || snapshot == nil) |
| 87 | && !isDeleting($0.id.uuidString.lowercased()) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func isDeleting(_ itemID: String) -> Bool { |
| 92 | outbox.entries.contains { [.trashItem, .deleteItem, .skipIdea].contains($0.action) && $0.itemID == itemID && $0.error == nil |
| 93 | && ($0.account == nil || $0.account == account) |
| 94 | && ($0.workspaceID == nil || $0.workspaceID == snapshot?.workspaceID) } |
| 95 | } |
| 96 | |
| 97 | func skipPendingIdea(_ entry: CompanionLibraryOutbox.Entry) throws { |
| 98 | try loadOutbox() |
| 99 | guard !isDeleting(entry.id.uuidString.lowercased()) else { return } |
| 100 | try queue(.init(id: UUID(), action: .trashItem, itemID: entry.id.uuidString.lowercased(), |
| 101 | revision: "pending-add", title: "", text: "", workspaceID: entry.workspaceID, account: entry.account)) |
| 102 | } |
| 103 | |
| 104 | var canUseAgentFeatures: Bool { |
| 105 | guard let snapshot, snapshot.enabled else { return false } |
| 106 | return snapshot.supportsAgentFeatures == true |
| 107 | } |
| 108 | |
| 109 | func revisionRequests(for item: CompanionLibrary.Item) -> [StudioWritingRequest] { |
| 110 | let current = (snapshot?.items ?? []).first { $0.id == item.id } |
| 111 | ?? (snapshot?.newsletters ?? []).first { $0.id == item.id } |
| 112 | ?? (snapshot?.scripts ?? []).first { $0.id == item.id } |
| 113 | ?? (snapshot?.articles ?? []).first { $0.id == item.id } |
| 114 | ?? item |
| 115 | let saved = current.revisionRequests?.map(StudioWritingRequest.init) ?? current.notes.enumerated().map { index, text in |
| 116 | let raw = current.noteStates?.indices.contains(index) == true ? current.noteStates?[index] : nil |
| 117 | let state: CompanionLibrary.RevisionRequest.State = switch raw { |
| 118 | case "applied": .actedOn |
| 119 | case "pending": .pending |
| 120 | case "waitingForDraft": .waitingForEditable |
| 121 | default: .savedNote |
| 122 | } |
| 123 | let date = current.noteDates?.indices.contains(index) == true ? current.noteDates?[index] : nil |
| 124 | return StudioWritingRequest(.init(id: "legacy-\(index)", text: text, date: date, state: state)) |
| 125 | } |
| 126 | let pending = pendingChanges(for: item.id) |
| 127 | let synced = Set(saved.map(\.id)) |
| 128 | let local: [StudioWritingRequest] = pending.compactMap { entry in |
| 129 | let id = entry.requestID.uuidString.lowercased() |
| 130 | guard entry.requestsWritingHelp == true, !synced.contains(id) else { return nil } |
| 131 | return StudioWritingRequest(id: id, text: entry.text, state: entry.error ?? "Waiting for your Mac to revise") |
| 132 | } |
| 133 | let withdrawals = pending.filter { $0.withdrawsRevision != nil } |
| 134 | let localIDs = Set(local.map(\.id)) |
| 135 | let cloud: [StudioWritingRequest] = (snapshot?.pending ?? []).compactMap { change in |
| 136 | let id = change.id.uuidString.lowercased() |
| 137 | guard change.itemID == item.id, change.requestsWritingHelp == true, |
| 138 | !synced.contains(id), !localIDs.contains(id) else { return nil } |
| 139 | return StudioWritingRequest(id: id, text: change.text, state: "Waiting for your Mac to revise") |
| 140 | } |
| 141 | let rows = (saved + local + cloud).map { original -> StudioWritingRequest in |
| 142 | var row = original |
| 143 | guard let target = UUID(uuidString: row.id), let workspaceID = snapshot?.workspaceID else { return row } |
| 144 | if let withdrawal = withdrawals.first(where: { $0.withdrawsRevision == target }) { |
| 145 | row.state = withdrawal.error ?? "Withdrawal pending on Mac" |
| 146 | } else if row.state != StudioRevisionRequestCopy.actedOn, |
| 147 | snapshot?.supportsRevisionWithdrawal == true || pending.contains(where: { |
| 148 | $0.requestID == target && $0.requestsWritingHelp == true && $0.revisionPrepared == false |
| 149 | }) { |
| 150 | row.withdraw = { [weak self] in |
| 151 | try self?.withdrawRevision(target, itemID: item.id, workspaceID: workspaceID) |
| 152 | } |
| 153 | } |
| 154 | return row |
| 155 | } |
| 156 | let visibleIDs = Set(rows.map(\.id)) |
| 157 | return rows + withdrawals.compactMap { entry in |
| 158 | guard let target = entry.withdrawsRevision, !visibleIDs.contains(target.uuidString.lowercased()) else { return nil } |
| 159 | return StudioWritingRequest(id: target.uuidString.lowercased(), text: "Revision request", |
| 160 | state: entry.error ?? "Withdrawal pending on Mac") |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private func withdrawRevision(_ target: UUID, itemID: String, workspaceID: UUID) throws { |
| 165 | guard let account, let snapshot, snapshot.workspaceID == workspaceID else { throw CompanionLibraryError.disabled } |
| 166 | try loadOutbox() |
| 167 | var next = outbox |
| 168 | try next.withdrawRevision(target, itemID: itemID, workspaceID: workspaceID, account: account, |
| 169 | supportedByMac: snapshot.supportsRevisionWithdrawal == true) |
| 170 | try persist(next) |
| 171 | if busy { newsletterRefreshPending = true } |
| 172 | else { Task { await refresh() } } |
| 173 | } |
| 174 | |
| 175 | var pendingMediaDrafts: [CompanionLibraryOutbox.Entry] { |
| 176 | outbox.entries.filter { $0.mediaDraft != nil && $0.workspaceID == snapshot?.workspaceID && $0.account == account } |
| 177 | } |
| 178 | |
| 179 | var pendingQuickXPosts: [CompanionLibraryOutbox.Entry] { |
| 180 | outbox.entries.filter { $0.quickXAccountKey != nil && $0.workspaceID == snapshot?.workspaceID && $0.account == account } |
| 181 | } |
| 182 | |
| 183 | func lastUpdated(_ item: CompanionLibrary.Item) -> Date? { |
| 184 | let savedEdit = pendingChanges(for: item.id).last { |
| 185 | ($0.action == .editIdea || $0.action == .editDraft) && $0.error == nil |
| 186 | }?.savedAt |
| 187 | let localCreation = item.revision == "pending-add" |
| 188 | ? outbox.entries.first { $0.id.uuidString.lowercased() == item.id }?.savedAt |
| 189 | : nil |
| 190 | return [savedEdit, localCreation, item.revisionDate].compactMap { $0 }.max() |
| 191 | } |
| 192 | |
| 193 | func lastUpdated(_ itemID: String, in workspaceID: UUID) -> Date? { |
| 194 | guard let snapshot, snapshot.workspaceID == workspaceID, |
| 195 | let item = (snapshot.items + (snapshot.newsletters ?? []) + (snapshot.articles ?? [])) |
| 196 | .first(where: { $0.id == itemID }) else { return nil } |
| 197 | return lastUpdated(item) |
| 198 | } |
| 199 | |
| 200 | func imagePreview(_ itemID: String, in workspaceID: UUID) -> Data? { |
| 201 | guard let snapshot, snapshot.workspaceID == workspaceID else { return nil } |
| 202 | return snapshot.imagePreview(for: itemID) |
| 203 | } |
| 204 | |
| 205 | func pendingChanges(for itemID: String) -> [CompanionLibraryOutbox.Entry] { |
| 206 | outbox.entries.filter { |
| 207 | $0.itemID == itemID && $0.workspaceID == snapshot?.workspaceID && $0.account == account |
| 208 | && $0.action != .saveRevision |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | private func historyURL(workspaceID: UUID, account: String) -> URL { |
| 213 | let scope = SHA256.hash(data: Data((account + workspaceID.uuidString).utf8)).map { String(format: "%02x", $0) }.joined() |
| 214 | return URL.applicationSupportDirectory.appending(path: "Inkspring/Revisions/\(scope).json") |
| 215 | } |
| 216 | |
| 217 | private func localHistory(workspaceID: UUID, account: String) throws -> [String: [ContentRevision]] { |
| 218 | let url = historyURL(workspaceID: workspaceID, account: account) |
| 219 | guard FileManager.default.fileExists(atPath: url.path) else { return [:] } |
| 220 | return try JSONDecoder().decode([String: [ContentRevision]].self, from: Data(contentsOf: url)) |
| 221 | } |
| 222 | |
| 223 | func history(for item: CompanionLibrary.Item) throws -> [ContentRevision] { |
| 224 | guard let snapshot, let account else { return item.history ?? [] } |
| 225 | let local = try localHistory(workspaceID: snapshot.workspaceID, account: account)[item.id] ?? [] |
| 226 | let current = (snapshot.items + (snapshot.newsletters ?? []) + (snapshot.scripts ?? []) + (snapshot.articles ?? [])).first { $0.id == item.id } ?? item |
| 227 | let all = (current.history ?? []) + local |
| 228 | return Dictionary(all.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }).values |
| 229 | .sorted { ($0.savedAt ?? "") > ($1.savedAt ?? "") } |
| 230 | } |
| 231 | |
| 232 | private func recordHistory(_ entry: CompanionLibraryOutbox.Entry) throws { |
| 233 | guard entry.action == .editDraft, let itemID = entry.itemID, let workspaceID = entry.workspaceID, |
| 234 | let account = entry.account, |
| 235 | let item = ((snapshot?.items ?? []) + (snapshot?.newsletters ?? []) + (snapshot?.scripts ?? []) + (snapshot?.articles ?? [])).first(where: { $0.id == itemID }) else { return } |
| 236 | var archive = try localHistory(workspaceID: workspaceID, account: account) |
| 237 | var versions = archive[itemID] ?? [] |
| 238 | if !item.shortened, !(versions + (item.history ?? [])).contains(where: { $0.text == item.body && $0.savedAt == item.revision }) { |
| 239 | versions.append(.init(savedAt: item.revision, title: item.title, text: item.body, |
| 240 | format: item.format, source: "Mac")) |
| 241 | } |
| 242 | versions.append(.init(id: entry.id.uuidString, savedAt: entry.savedAt?.ISO8601Format(.init(includingFractionalSeconds: true)), |
| 243 | title: entry.title.isEmpty ? item.title : entry.title, text: entry.text, |
| 244 | format: entry.xFormat ?? item.format, subtitle: entry.subtitle ?? item.history?.first?.subtitle, |
| 245 | source: UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone")) |
| 246 | archive[itemID] = versions |
| 247 | let url = historyURL(workspaceID: workspaceID, account: account) |
| 248 | try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 249 | try JSONEncoder().encode(archive).write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) |
| 250 | } |
| 251 | |
| 252 | private func queueHistory(in library: CompanionLibrary, account: String, outbox: inout CompanionLibraryOutbox) throws { |
| 253 | guard library.supportsRevisionHistory == true else { return } |
| 254 | let items = library.items + (library.newsletters ?? []) + (library.scripts ?? []) + (library.articles ?? []) |
| 255 | let existing = Set(items.flatMap { $0.history ?? [] }.map(\.id) + |
| 256 | library.pending.compactMap { $0.historySnapshot?.id } + outbox.entries.compactMap { $0.historySnapshot?.id }) |
| 257 | for (itemID, revisions) in try localHistory(workspaceID: library.workspaceID, account: account) { |
| 258 | guard items.contains(where: { $0.id == itemID }) else { continue } |
| 259 | for revision in revisions where !existing.contains(revision.id) { |
| 260 | outbox.entries.append(.init(id: UUID(), action: .saveRevision, itemID: itemID, revision: "", |
| 261 | title: "", text: "", workspaceID: library.workspaceID, account: account, historySnapshot: revision)) |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | enum NewsletterSyncStatus: String { |
| 267 | case savedOnDevice = "Saved on this device" |
| 268 | case needsMacUpdate = "Mac update needed" |
| 269 | case waitingForMac = "Waiting for Mac" |
| 270 | case needsReview = "Edit needs review" |
| 271 | |
| 272 | var icon: String { |
| 273 | switch self { |
| 274 | case .savedOnDevice, .waitingForMac: "clock" |
| 275 | case .needsMacUpdate: "arrow.down.circle" |
| 276 | case .needsReview: "exclamationmark.circle" |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | func newsletterSyncStatus(for entry: CompanionLibraryOutbox.Entry) -> NewsletterSyncStatus { |
| 282 | if entry.error != nil { return .needsReview } |
| 283 | if entry.change?.needsWritingTools == true && snapshot?.supportsWritingTools != true || (entry.editsScript == true ? snapshot?.supportsScripts != true : snapshot?.supportsNewsletterEdits != true) { return .needsMacUpdate } |
| 284 | if snapshot?.pending.contains(where: { $0.id == entry.requestID }) == true { return .waitingForMac } |
| 285 | return .savedOnDevice |
| 286 | } |
| 287 | |
| 288 | var newsletterSyncSummary: String? { |
| 289 | guard let snapshot else { return nil } |
| 290 | let edits = outbox.entries.filter { |
| 291 | $0.isLongFormEdit && $0.workspaceID == snapshot.workspaceID && $0.account == account |
| 292 | } |
| 293 | let latestByItem = Dictionary(edits.compactMap { edit in edit.itemID.map { ($0, edit) } }, |
| 294 | uniquingKeysWith: { _, newest in newest }) |
| 295 | let statuses = latestByItem.values.map(newsletterSyncStatus) |
| 296 | if statuses.contains(.needsReview) { return NewsletterSyncStatus.needsReview.rawValue } |
| 297 | if snapshot.supportsNewsletterEdits != true { return NewsletterSyncStatus.needsMacUpdate.rawValue } |
| 298 | if statuses.contains(.savedOnDevice) { return NewsletterSyncStatus.savedOnDevice.rawValue } |
| 299 | if statuses.contains(.waitingForMac) { return NewsletterSyncStatus.waitingForMac.rawValue } |
| 300 | if error != nil { return "Check failed" } |
| 301 | return "Up to date" |
| 302 | } |
| 303 | |
| 304 | struct SchedulingRequest: Identifiable { |
| 305 | let item: CompanionLibrary.Item |
| 306 | let hour: Date |
| 307 | let error: String? |
| 308 | let requestedAt: Date? |
| 309 | var id: String { item.id } |
| 310 | } |
| 311 | |
| 312 | var pendingSchedules: [SchedulingRequest] { |
| 313 | (snapshot?.items ?? []).compactMap { item in |
| 314 | guard let entry = pendingChanges(for: item.id).last(where: { $0.action == .scheduleDraft }), |
| 315 | let hour = entry.change?.postingHour else { return nil } |
| 316 | return SchedulingRequest(item: item, hour: hour, error: entry.error, requestedAt: entry.savedAt) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | var visibleItems: [CompanionLibrary.Item] { |
| 321 | let remote: [CompanionLibrary.Item] = (snapshot?.items ?? []).compactMap { original in |
| 322 | var item = original |
| 323 | for change in pendingChanges(for: item.id) where change.error == nil { |
| 324 | switch change.action { |
| 325 | case .trashItem, .skipIdea: item.isTrashed = true |
| 326 | case .restoreItem, .restoreIdea: item.isTrashed = false |
| 327 | case .deleteItem: return nil |
| 328 | default: break |
| 329 | } |
| 330 | } |
| 331 | return item |
| 332 | } |
| 333 | let remoteIDs = Set(remote.map(\.id)) |
| 334 | let local = pendingIdeas.compactMap { entry -> CompanionLibrary.Item? in |
| 335 | let id = entry.id.uuidString.lowercased() |
| 336 | guard !remoteIDs.contains(id) else { return nil } |
| 337 | var item = CompanionLibrary.Item(id: id, revision: "pending-add", kind: .idea, |
| 338 | projectID: entry.itemID ?? snapshot?.projects.first?.id ?? "", title: entry.title, body: entry.text, |
| 339 | shortened: false, platform: "", status: "draft", notes: []) |
| 340 | item.generationStatus = entry.error ?? (snapshot == nil ? "Saved on this device" : "Waiting for your Mac to sync this idea") |
| 341 | item.planMarkdown = entry.initialPlan |
| 342 | return item |
| 343 | } |
| 344 | return local + remote |
| 345 | } |
| 346 | |
| 347 | func isChanging(_ itemID: String) -> Bool { |
| 348 | pendingChanges(for: itemID).contains { !([CompanionLibrary.Change.Action.note, .saveRevision].contains($0.action)) && $0.error == nil } |
| 349 | || snapshot?.pending.contains { $0.itemID == itemID && !([CompanionLibrary.Change.Action.note, .saveRevision].contains($0.action)) } == true |
| 350 | } |
| 351 | |
| 352 | func canDelete(_ itemID: String) -> Bool { |
| 353 | if !isChanging(itemID) { return true } |
| 354 | guard let move = pendingTrash(for: itemID) else { return false } |
| 355 | return pendingChanges(for: itemID).allSatisfy { $0.id == move.id || $0.action == .note || $0.error != nil } |
| 356 | && snapshot?.pending.contains { $0.itemID == itemID && $0.id != move.requestID && !([CompanionLibrary.Change.Action.note, .saveRevision].contains($0.action)) } != true |
| 357 | } |
| 358 | |
| 359 | private func pendingTrash(for itemID: String) -> CompanionLibraryOutbox.Entry? { |
| 360 | pendingChanges(for: itemID).last { $0.movesToTrash && $0.error == nil } |
| 361 | } |
| 362 | |
| 363 | var visibleScripts: [CompanionLibrary.Item] { |
| 364 | let remote = (snapshot?.scripts ?? []) + (snapshot?.articles ?? []).filter { $0.platform != "linkedin" } |
| 365 | let ids = Set((remote + (snapshot?.newsletters ?? [])).map(\.id)) |
| 366 | let local = outbox.entries.filter { |
| 367 | $0.createsScript == true && $0.account == account && $0.workspaceID == snapshot?.workspaceID |
| 368 | && !ids.contains($0.id.uuidString.lowercased()) |
| 369 | }.map { entry in |
| 370 | CompanionLibrary.Item(id: entry.id.uuidString.lowercased(), revision: "pending-add", kind: mobileWritingKind(entry.writingKind), |
| 371 | projectID: entry.itemID ?? "", title: entry.title, body: entry.text, shortened: false, |
| 372 | platform: mobileWritingPlatform(entry.writingKind), status: "draft", notes: []) |
| 373 | } |
| 374 | return remote + local |
| 375 | } |
| 376 | |
| 377 | func createScript(projectID: String, kind: String = "script") throws -> String { |
| 378 | guard let snapshot else { throw CompanionScheduleError.changed } |
| 379 | let title = kind == "newsletter" ? "Untitled newsletter" : kind == "script" ? "Untitled YouTube script" : |
| 380 | "Untitled \(reviewPlatformName(mobileWritingPlatform(kind))) article" |
| 381 | let change = CompanionLibrary.Change(action: .addIdea, itemID: projectID, title: title, createsScript: true, writingKind: kind) |
| 382 | try saveChange(change, workspaceID: snapshot.workspaceID) |
| 383 | return change.id.uuidString.lowercased() |
| 384 | } |
| 385 | |
| 386 | @discardableResult |
| 387 | func saveIdea(title: String, text: String, projectID: String?, plan: String? = nil) throws -> String { |
| 388 | let id = UUID() |
| 389 | try queue(.init(id: id, action: .addIdea, itemID: projectID, revision: "", title: title, text: text, |
| 390 | workspaceID: snapshot?.workspaceID, account: account, initialPlan: plan)) |
| 391 | return id.uuidString.lowercased() |
| 392 | } |
| 393 | |
| 394 | func saveChange(_ change: CompanionLibrary.Change, workspaceID: UUID) throws { |
| 395 | guard let account, snapshot?.workspaceID == workspaceID else { throw CompanionScheduleError.changed } |
| 396 | guard !change.usesMacAgent || canUseAgentFeatures else { throw CompanionLibraryError.disabled } |
| 397 | guard change.ideaDraftPlatforms == nil || snapshot?.supportsClaudeIdeaDrafts == true else { |
| 398 | throw CompanionLibraryError.macUpdateForIdeaDrafts |
| 399 | } |
| 400 | if let selection = change.writingSelection { |
| 401 | guard let provider = snapshot?.writingProviders?.first(where: { $0.id == selection.provider }), provider.isAvailable, |
| 402 | selection.model.map({ id in provider.models.contains { $0.id == id } }) ?? true else { |
| 403 | throw CompanionLibraryError.disabled |
| 404 | } |
| 405 | } |
| 406 | guard change.mediaDraft == nil || snapshot?.supportsMediaDrafts == true else { throw CompanionLibraryError.disabled } |
| 407 | guard change.quickXAccountKey == nil || snapshot?.supportsQuickXPost == true else { throw CompanionLibraryError.disabled } |
| 408 | guard change.ideaImagePrompt == nil || snapshot?.ideaImageProvider != nil else { throw CompanionLibraryError.disabled } |
| 409 | guard change.valid else { throw CompanionLibraryError.invalid } |
| 410 | if change.isLongFormEdit, try JSONEncoder().encode(change).count > change.payloadLimit { |
| 411 | throw CompanionLibraryError.invalid |
| 412 | } |
| 413 | if change.action == .scheduleDraft, snapshot?.postingWindows == nil { throw CompanionLibraryError.disabled } |
| 414 | let afterTrash = change.action == .deleteItem ? pendingTrash(for: change.itemID)?.id : nil |
| 415 | let creation = change.isLongFormEdit || change.requestsWritingHelp == true ? outbox.entries.last { |
| 416 | $0.createsScript == true && $0.id.uuidString.lowercased() == change.itemID && $0.account == account |
| 417 | && $0.workspaceID == workspaceID |
| 418 | }?.requestID : nil |
| 419 | let predecessor = change.requestsWritingHelp == true ? outbox.entries.last { |
| 420 | $0.action == .editDraft && $0.itemID == change.itemID && $0.account == account && $0.workspaceID == workspaceID && $0.error == nil |
| 421 | }?.requestID ?? creation : creation |
| 422 | try queue(.init(id: change.id, action: change.action, itemID: change.itemID, revision: change.revision, |
| 423 | title: change.title, text: change.text, workspaceID: workspaceID, account: account, |
| 424 | afterTrash: afterTrash, publishesXArticle: change.publishesXArticle, xArticleAccountKey: change.xArticleAccountKey, requestsWritingHelp: change.requestsWritingHelp, writingKind: change.writingKind, baseScriptTitle: change.baseScriptTitle, editsScript: change.editsScript, createsScript: change.createsScript, editsNewsletter: change.editsNewsletter, afterNewsletterEdit: predecessor, |
| 425 | baseNewsletterText: change.baseNewsletterText, xFormat: change.xFormat, generatesXDraft: change.generatesXDraft, |
| 426 | restoresRevision: change.restoresRevision, subtitle: change.subtitle, contentOperation: change.contentOperation, basePlan: change.basePlan, initialPlan: change.initialPlan, |
| 427 | ideaDraftPlatforms: change.ideaDraftPlatforms, writingSelection: change.writingSelection, |
| 428 | mediaDraft: change.mediaDraft, ideaImagePrompt: change.ideaImagePrompt, quickXAccountKey: change.quickXAccountKey)) |
| 429 | } |
| 430 | |
| 431 | func queueQuickXPost(text: String, projectID: String, accountKey: String) throws -> UUID { |
| 432 | guard let snapshot, snapshot.supportsQuickXPost == true, snapshot.xArticleAccountKey == accountKey else { |
| 433 | throw CompanionLibraryError.disabled |
| 434 | } |
| 435 | var request = CompanionLibrary.Change(action: .note, itemID: projectID, text: text) |
| 436 | request.quickXAccountKey = accountKey |
| 437 | try saveChange(request, workspaceID: snapshot.workspaceID) |
| 438 | return request.id |
| 439 | } |
| 440 | |
| 441 | private func mediaOutboxURL(_ id: UUID) -> URL { |
| 442 | URL.applicationSupportDirectory.appending(path: "Inkspring/Media Outbox/\(id.uuidString.lowercased())") |
| 443 | } |
| 444 | |
| 445 | func queueMediaDraft(file: URL, platform: String, caption: String, projectID: String, ideaID: String? = nil) throws { |
| 446 | guard let snapshot else { throw CompanionScheduleError.changed } |
| 447 | let opened = file.startAccessingSecurityScopedResource() |
| 448 | defer { if opened { file.stopAccessingSecurityScopedResource() } } |
| 449 | let attributes = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) |
| 450 | guard attributes.isRegularFile == true, let size = attributes.fileSize, |
| 451 | (1...CompanionLibrary.MediaDraft.limit).contains(size) else { throw CompanionLibraryError.invalid } |
| 452 | let data = try Data(contentsOf: file, options: .mappedIfSafe) |
| 453 | let name = file.lastPathComponent.trimmingCharacters(in: .whitespacesAndNewlines) |
| 454 | var change = CompanionLibrary.Change(action: .note, itemID: projectID, title: name, text: caption) |
| 455 | change.mediaDraft = .init(platform: platform, fileName: name, data: data, ideaID: ideaID) |
| 456 | guard change.valid else { throw CompanionLibraryError.invalid } |
| 457 | let destination = mediaOutboxURL(change.id) |
| 458 | try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 459 | try data.write(to: destination, options: .atomic) |
| 460 | do { try saveChange(change, workspaceID: snapshot.workspaceID) } |
| 461 | catch { |
| 462 | try? FileManager.default.removeItem(at: destination) |
| 463 | throw error |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | private func queue(_ change: CompanionLibraryOutbox.Entry) throws { |
| 468 | try loadOutbox() |
| 469 | var entry = change |
| 470 | entry.savedAt = .now |
| 471 | if entry.requestsWritingHelp == true { entry.revisionPrepared = false } |
| 472 | try recordHistory(entry) |
| 473 | var next = outbox |
| 474 | if entry.action == .editDraft { |
| 475 | next.queueNewsletterEdit(entry) |
| 476 | } else { |
| 477 | if entry.ideaDraftPlatforms != nil { |
| 478 | next.entries.removeAll { |
| 479 | $0.ideaDraftPlatforms != nil && $0.itemID == entry.itemID && $0.workspaceID == entry.workspaceID |
| 480 | && $0.account == entry.account && $0.error != nil |
| 481 | } |
| 482 | } |
| 483 | if entry.ideaImagePrompt != nil { |
| 484 | next.entries.removeAll { |
| 485 | $0.ideaImagePrompt != nil && $0.itemID == entry.itemID && $0.workspaceID == entry.workspaceID |
| 486 | && $0.account == entry.account && $0.error != nil |
| 487 | } |
| 488 | } |
| 489 | if [.editDraft, .editIdea, .trashItem, .restoreItem, .deleteItem, .scheduleDraft].contains(entry.action) { |
| 490 | next.entries.removeAll { |
| 491 | $0.action == entry.action && $0.contentOperation == entry.contentOperation |
| 492 | && $0.editsNewsletter == entry.editsNewsletter && $0.itemID == entry.itemID && $0.workspaceID == entry.workspaceID |
| 493 | && $0.account == entry.account && $0.error != nil |
| 494 | } |
| 495 | } |
| 496 | next.entries.append(entry) |
| 497 | } |
| 498 | try persist(next) |
| 499 | if (entry.isLongFormEdit || entry.requestsWritingHelp == true || entry.publishesXArticle == true |
| 500 | || entry.ideaDraftPlatforms != nil || entry.mediaDraft != nil || entry.quickXAccountKey != nil |
| 501 | || entry.ideaImagePrompt != nil) && busy { |
| 502 | newsletterRefreshPending = true |
| 503 | } else { |
| 504 | Task { await refresh() } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | private func loadOutbox() throws { |
| 509 | guard !outboxLoaded else { return } |
| 510 | if let data = defaults.data(forKey: Self.outboxKey) { |
| 511 | state.outbox = try JSONDecoder().decode(CompanionLibraryOutbox.self, from: data) |
| 512 | } else if let data = defaults.data(forKey: Self.legacyIdeasKey), !data.isEmpty { |
| 513 | var migrated = outbox |
| 514 | try migrated.migrateIdeas(from: data) |
| 515 | try persist(migrated) |
| 516 | } |
| 517 | outboxLoaded = true |
| 518 | } |
| 519 | |
| 520 | private func persist(_ value: CompanionLibraryOutbox) throws { |
| 521 | defaults.set(try JSONEncoder().encode(value), forKey: Self.outboxKey) |
| 522 | state.outbox = value |
| 523 | } |
| 524 | |
| 525 | #if DEBUG |
| 526 | private func prepareChanges(in library: CompanionLibrary, account: String) throws -> [CompanionLibrary.Change] { |
| 527 | var next = outbox |
| 528 | try queueHistory(in: library, account: account, outbox: &next) |
| 529 | let changes = next.prepare(for: library, account: account) |
| 530 | try persist(next) |
| 531 | return changes |
| 532 | } |
| 533 | #endif |
| 534 | |
| 535 | private func acceptSnapshot(_ incoming: CompanionLibrary, account: String) throws -> [CompanionLibrary.Change] { |
| 536 | guard !isOlderSnapshot(incoming) else { return [] } |
| 537 | var next = outbox |
| 538 | try queueHistory(in: incoming, account: account, outbox: &next) |
| 539 | let changes = next.prepare(for: incoming, account: account) |
| 540 | let completedMedia = outbox.entries.filter { entry in |
| 541 | entry.mediaDraft != nil && incoming.results.contains { $0.id == entry.requestID && $0.error == nil } |
| 542 | } |
| 543 | if next != outbox { defaults.set(try JSONEncoder().encode(next), forKey: Self.outboxKey) } |
| 544 | if snapshot != incoming || next != outbox { |
| 545 | // Clearing an acknowledged local edit must replace the displayed text in the same update. |
| 546 | state = LibraryState(snapshot: incoming, outbox: next) |
| 547 | } |
| 548 | for entry in completedMedia { try? FileManager.default.removeItem(at: mediaOutboxURL(entry.id)) } |
| 549 | return changes |
| 550 | } |
| 551 | |
| 552 | private func isOlderSnapshot(_ incoming: CompanionLibrary) -> Bool { |
| 553 | guard let snapshot, incoming.workspaceID == snapshot.workspaceID else { return false } |
| 554 | if incoming.updatedAt < snapshot.updatedAt { return true } |
| 555 | let currentRevisions = Dictionary(((snapshot.newsletters ?? []) + (snapshot.scripts ?? []) + (snapshot.articles ?? [])).compactMap { item in |
| 556 | item.revisionDate.map { (item.id, $0) } |
| 557 | }, uniquingKeysWith: max) |
| 558 | return ((incoming.newsletters ?? []) + (incoming.scripts ?? []) + (incoming.articles ?? [])).contains { item in |
| 559 | guard let current = currentRevisions[item.id], let incoming = item.revisionDate else { return false } |
| 560 | return incoming < current |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | private func clearSnapshot() { |
| 565 | state.snapshot = nil |
| 566 | syncedText = nil |
| 567 | } |
| 568 | |
| 569 | private func cloud() -> CloudScheduleStore { |
| 570 | if let store { return store } |
| 571 | let value = CloudScheduleStore() |
| 572 | store = value |
| 573 | return value |
| 574 | } |
| 575 | |
| 576 | func refresh() async { |
| 577 | guard !busy else { return } |
| 578 | busy = true |
| 579 | syncErrorCode = nil |
| 580 | let revision = accountRevision |
| 581 | var checkedAccount = false |
| 582 | defer { |
| 583 | busy = false |
| 584 | let refreshAgain = newsletterRefreshPending || revision != accountRevision |
| 585 | newsletterRefreshPending = false |
| 586 | if refreshAgain { |
| 587 | Task { await refresh() } |
| 588 | } else if !Task.isCancelled { |
| 589 | lastCheck = .now |
| 590 | } |
| 591 | } |
| 592 | do { |
| 593 | try loadOutbox() |
| 594 | #if DEBUG |
| 595 | if lastCheck == nil, ProcessInfo.processInfo.arguments.contains("--initial-load-fixture") { |
| 596 | try await Task.sleep(for: .seconds(4)) |
| 597 | } |
| 598 | if ProcessInfo.processInfo.arguments.contains("--unpaired-fixture") { return } |
| 599 | if ProcessInfo.processInfo.arguments.contains("--library-fixture") { |
| 600 | account = "fixture" |
| 601 | if var stale = staleFixtureSnapshot { |
| 602 | staleFixtureSnapshot = nil |
| 603 | stale.updatedAt = .now |
| 604 | _ = try acceptSnapshot(stale, account: "fixture") |
| 605 | return |
| 606 | } |
| 607 | var fixture = snapshot ?? Self.fixture |
| 608 | for change in try prepareChanges(in: fixture, account: "fixture") { |
| 609 | do { try fixture.enqueue(change) } catch CompanionLibraryError.full { break } |
| 610 | } |
| 611 | if ProcessInfo.processInfo.arguments.contains("--quick-x-fixture") { |
| 612 | fixture.acknowledge(fixture.pending.filter { $0.quickXAccountKey != nil } |
| 613 | .map { .init(id: $0.id, publicationURL: "https://x.com/i/web/status/789") }) |
| 614 | } |
| 615 | if ProcessInfo.processInfo.arguments.contains("--idea-draft-result-fixture") { |
| 616 | let requests = fixture.pending.filter { $0.ideaDraftPlatforms == ["x"] && $0.xFormat == "post" } |
| 617 | for change in requests { |
| 618 | guard let index = fixture.items.firstIndex(where: { $0.id == change.itemID }) else { continue } |
| 619 | let id = change.id.uuidString.lowercased() |
| 620 | fixture.items[index].draftedIdeaPlatforms = ["x"] |
| 621 | fixture.items[index].draftedIdeaIDs = ["x": id] |
| 622 | var draft = CompanionLibrary.Item(id: id, revision: "2026-11-21T12:00:00.000Z", kind: .draft, |
| 623 | projectID: fixture.items[index].projectID, title: "Show the unfinished work", |
| 624 | body: "Show one trade-off from your work in progress.", shortened: false, platform: "x", status: "ready", notes: []) |
| 625 | draft.format = "post" |
| 626 | fixture.items.append(draft) |
| 627 | } |
| 628 | fixture.acknowledge(requests.map { .init(id: $0.id) }) |
| 629 | } |
| 630 | if ProcessInfo.processInfo.arguments.contains("--idea-first-fixture") { |
| 631 | let additions = fixture.pending.filter { $0.action == .addIdea && $0.createsScript != true } |
| 632 | for change in additions { |
| 633 | fixture.items.insert(.init(id: change.id.uuidString.lowercased(), |
| 634 | revision: Date.now.ISO8601Format(.init(includingFractionalSeconds: true)), kind: .idea, |
| 635 | projectID: change.itemID, title: change.title, body: change.text, |
| 636 | shortened: false, platform: "", status: "draft", notes: []), at: 0) |
| 637 | } |
| 638 | fixture.acknowledge(additions.map { .init(id: $0.id) }) |
| 639 | } |
| 640 | if ProcessInfo.processInfo.arguments.contains("--history-fixture") { |
| 641 | for change in fixture.pending where change.action == .saveRevision || change.action == .editDraft && change.editsNewsletter != true { |
| 642 | guard let index = fixture.items.firstIndex(where: { $0.id == change.itemID }) else { continue } |
| 643 | if let history = change.historySnapshot { |
| 644 | if fixture.items[index].history?.contains(where: { $0.id == history.id }) != true { |
| 645 | fixture.items[index].history = (fixture.items[index].history ?? []) + [history] |
| 646 | } |
| 647 | } else { |
| 648 | let item = fixture.items[index] |
| 649 | var updated = CompanionLibrary.Item(id: item.id, revision: Date.now.ISO8601Format(.init(includingFractionalSeconds: true)), |
| 650 | kind: item.kind, projectID: item.projectID, title: change.title, body: change.text, |
| 651 | shortened: false, platform: item.platform, status: item.status, notes: item.notes, referenceID: item.referenceID) |
| 652 | updated.format = change.xFormat ?? item.format |
| 653 | updated.history = item.history |
| 654 | fixture.items[index] = updated |
| 655 | } |
| 656 | fixture.results.append(.init(id: change.id)) |
| 657 | } |
| 658 | let completed = Set(fixture.results.map(\.id)) |
| 659 | fixture.pending.removeAll { completed.contains($0.id) } |
| 660 | fixture.updatedAt = .now |
| 661 | } |
| 662 | if ProcessInfo.processInfo.arguments.contains("--withdraw-revision-fixture"), |
| 663 | let index = fixture.items.firstIndex(where: { $0.kind == .idea }) { |
| 664 | if fixture.items[index].revisionRequests == nil { |
| 665 | fixture.items[index].revisionRequests = [ |
| 666 | .init(id: "7ac22da9-1ef6-4dbd-8913-9b9caa03ec64", text: "Shorten the introduction.", date: nil, state: .pending), |
| 667 | .init(id: "6b5734c1-bc62-49d3-99c6-94829fd30008", text: "Keep the research citations.", date: nil, state: .actedOn) |
| 668 | ] |
| 669 | } |
| 670 | let withdrawals = fixture.pending.filter { $0.itemID == fixture.items[index].id && $0.withdrawsRevision != nil } |
| 671 | let ids = Set(withdrawals.compactMap { $0.withdrawsRevision?.uuidString.lowercased() }) |
| 672 | fixture.items[index].revisionRequests?.removeAll { ids.contains($0.id) } |
| 673 | fixture.acknowledge(withdrawals.map { .init(id: $0.id) }) |
| 674 | } |
| 675 | if ProcessInfo.processInfo.arguments.contains("--revision-requests-fixture"), |
| 676 | let index = fixture.items.firstIndex(where: { $0.kind == .idea }) { |
| 677 | let itemID = fixture.items[index].id |
| 678 | let requests = fixture.pending.filter { $0.itemID == itemID && $0.requestsWritingHelp == true } |
| 679 | if requests.count >= 2 { |
| 680 | fixture.items[index].revisionRequests = requests.map { |
| 681 | .init(id: $0.id.uuidString.lowercased(), text: $0.text, date: nil, state: .actedOn) |
| 682 | } |
| 683 | let ids = Set(requests.map(\.id)) |
| 684 | fixture.results += requests.map { .init(id: $0.id) } |
| 685 | fixture.pending.removeAll { ids.contains($0.id) } |
| 686 | fixture.updatedAt = .now |
| 687 | } |
| 688 | } |
| 689 | if ProcessInfo.processInfo.arguments.contains("--script-fixture") { |
| 690 | var writing = (fixture.scripts ?? []) + (fixture.articles ?? []) + (fixture.newsletters ?? []) |
| 691 | for change in fixture.pending where change.createsScript == true || change.isLongFormEdit || change.action == .saveRevision || change.requestsWritingHelp == true || change.publishesXArticle == true { |
| 692 | let id = change.createsScript == true ? change.id.uuidString.lowercased() : change.itemID |
| 693 | if let index = writing.firstIndex(where: { $0.id == id }) { |
| 694 | let item = writing[index] |
| 695 | var updated = CompanionLibrary.Item(id: id, revision: Date.now.ISO8601Format(.init(includingFractionalSeconds: true)), kind: item.kind, |
| 696 | projectID: item.projectID, title: change.title.isEmpty ? item.title : change.title, |
| 697 | body: change.requestsWritingHelp == true ? "# Local AI models\n\nA short brief explaining how local models run on your own hardware, where they help, and what to test." : change.action == .saveRevision || change.publishesXArticle == true ? item.body : change.text, |
| 698 | shortened: false, platform: item.platform, status: change.publishesXArticle == true ? "published" : "draft", notes: change.requestsWritingHelp == true ? item.notes + [change.text] : item.notes, referenceID: item.referenceID) |
| 699 | updated.publicationStatus = change.publishesXArticle == true ? "published" : item.publicationStatus |
| 700 | updated.publicationURL = change.publishesXArticle == true ? "https://x.com/i/web/status/789" : item.publicationURL |
| 701 | updated.history = item.history ?? [] |
| 702 | updated.noteStates = item.noteStates |
| 703 | updated.writingReply = item.writingReply |
| 704 | if change.requestsWritingHelp == true { updated.noteStates = Array(repeating: "applied", count: updated.notes.count); updated.writingReply = "Wrote a short brief about local AI models." } |
| 705 | if let revision = change.historySnapshot, updated.history?.contains(where: { $0.id == revision.id }) != true { |
| 706 | updated.history?.append(revision) |
| 707 | } |
| 708 | writing[index] = updated |
| 709 | } else if change.createsScript == true { |
| 710 | writing.append(.init(id: id, revision: Date.now.ISO8601Format(.init(includingFractionalSeconds: true)), kind: mobileWritingKind(change.writingKind), |
| 711 | projectID: change.itemID, title: change.title, body: change.text, shortened: false, platform: mobileWritingPlatform(change.writingKind), status: "draft", notes: [], referenceID: "STU–003")) |
| 712 | } else { continue } |
| 713 | fixture.results.append(.init(id: change.id, newsletterRevision: writing.first { $0.id == id }?.revision)) |
| 714 | } |
| 715 | fixture.scripts = writing.filter { $0.kind == .script } |
| 716 | fixture.articles = writing.filter { $0.kind == .article } |
| 717 | fixture.newsletters = writing.filter { $0.kind == .newsletter } |
| 718 | let completed = Set(fixture.results.map(\.id)) |
| 719 | fixture.pending.removeAll { completed.contains($0.id) } |
| 720 | } |
| 721 | let newsletterEdits = fixture.pending.filter { $0.editsNewsletter == true } |
| 722 | let exercisesSyncRace = ProcessInfo.processInfo.arguments.contains("--newsletter-sync-race-fixture") |
| 723 | for change in newsletterEdits { |
| 724 | if let index = fixture.newsletters?.firstIndex(where: { $0.id == change.itemID }) { |
| 725 | if exercisesSyncRace, let item = fixture.newsletters?[index] { |
| 726 | fixture.newsletters?[index] = .init( |
| 727 | id: item.id, revision: "2026-11-17T12:00:00.000Z", kind: item.kind, |
| 728 | projectID: item.projectID, title: item.title, |
| 729 | body: change.text + "\n\nApplied on Mac.\n\n" |
| 730 | + String(repeating: "This text is delivered separately through iCloud. ", count: 12), |
| 731 | shortened: false, platform: item.platform, status: item.status, notes: item.notes |
| 732 | ) |
| 733 | fixture.updatedAt = .now |
| 734 | staleFixtureSnapshot = snapshot |
| 735 | } else { |
| 736 | fixture.newsletters?[index].body = change.text |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | fixture.acknowledge(newsletterEdits.map { .init(id: $0.id) }) |
| 741 | let data = try fixture.separateFullText() |
| 742 | let completed = try await snapshotWithFullText(fixture) { _ in |
| 743 | if exercisesSyncRace && !newsletterEdits.isEmpty { try await Task.sleep(for: .seconds(3)) } |
| 744 | guard let data else { throw CompanionScheduleError.changed } |
| 745 | return data |
| 746 | } |
| 747 | _ = try acceptSnapshot(completed, account: "fixture") |
| 748 | accountStatus = "Preview data" |
| 749 | remoteWorkspaceFound = true |
| 750 | error = nil |
| 751 | return |
| 752 | } |
| 753 | #endif |
| 754 | let cloud = cloud() |
| 755 | let key = try await cloud.accountKey() |
| 756 | guard revision == accountRevision else { return } |
| 757 | checkedAccount = true |
| 758 | accountStatus = "Connected" |
| 759 | if account != key { |
| 760 | clearSnapshot() |
| 761 | remoteWorkspaceFound = nil |
| 762 | lastCloudContact = nil |
| 763 | } |
| 764 | account = key |
| 765 | let schedule = try await cloud.load(confirmedAccount: key) |
| 766 | guard revision == accountRevision else { return } |
| 767 | lastCloudContact = .now |
| 768 | remoteWorkspaceFound = schedule != nil |
| 769 | guard let schedule, schedule.sharing else { |
| 770 | clearSnapshot() |
| 771 | error = "Turn on schedule and library sync in Inkspring on your Mac." |
| 772 | return |
| 773 | } |
| 774 | if snapshot?.workspaceID != schedule.workspaceID { |
| 775 | clearSnapshot() |
| 776 | } |
| 777 | let incoming = try await cloud.loadLibrary(workspaceID: schedule.workspaceID, account: key) |
| 778 | guard revision == accountRevision else { return } |
| 779 | lastCloudContact = .now |
| 780 | guard let incoming, incoming.enabled else { |
| 781 | clearSnapshot() |
| 782 | error = CompanionLibraryError.disabled.localizedDescription |
| 783 | return |
| 784 | } |
| 785 | error = nil |
| 786 | guard !isOlderSnapshot(incoming) else { return } |
| 787 | let completed = try await snapshotWithFullText(incoming) { version in |
| 788 | try await cloud.loadLibraryText(version, workspaceID: incoming.workspaceID, account: key) |
| 789 | } |
| 790 | guard revision == accountRevision else { return } |
| 791 | let changes = try acceptSnapshot(completed, account: key) |
| 792 | let ready = changes.filter { $0.withdrawsRevision != nil } |
| 793 | + changes.filter { $0.withdrawsRevision == nil }.prefix(max(0, 24 - incoming.pending.count)) |
| 794 | if !ready.isEmpty { |
| 795 | for change in ready where change.mediaDraft != nil { |
| 796 | let data = try Data(contentsOf: mediaOutboxURL(change.id), options: .mappedIfSafe) |
| 797 | try await cloud.stageLibraryMedia(data, change: change, workspaceID: incoming.workspaceID, account: key) |
| 798 | } |
| 799 | _ = try await cloud.updateLibrary(workspaceID: incoming.workspaceID, account: key) { library in |
| 800 | for change in ready { |
| 801 | do { try library.enqueue(change) } |
| 802 | catch CompanionLibraryError.full { if change.withdrawsRevision == nil { break } } |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | } catch { |
| 807 | guard revision == accountRevision else { return } |
| 808 | let failure = error as NSError |
| 809 | syncErrorCode = "\(failure.domain) (\(failure.code))" |
| 810 | if !checkedAccount { accountStatus = "Unavailable" } |
| 811 | if (error as? CompanionScheduleError) == .accountChanged { |
| 812 | clearSnapshot() |
| 813 | account = nil |
| 814 | accountStatus = "Not checked" |
| 815 | remoteWorkspaceFound = nil |
| 816 | lastCloudContact = nil |
| 817 | } |
| 818 | self.error = error.localizedDescription |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | private func snapshotWithFullText(_ incoming: CompanionLibrary, |
| 823 | loadText: (CompanionLibrary.TextVersion) async throws -> Data) async throws -> CompanionLibrary { |
| 824 | guard let version = incoming.fullText else { |
| 825 | syncedText = nil |
| 826 | return incoming |
| 827 | } |
| 828 | let revision = accountRevision |
| 829 | let data: Data |
| 830 | if let syncedText, syncedText.workspace == incoming.workspaceID, syncedText.version == version { |
| 831 | data = syncedText.data |
| 832 | } else { |
| 833 | data = try await loadText(version) |
| 834 | } |
| 835 | let completed = try await Task.detached(priority: .utility) { |
| 836 | var completed = incoming |
| 837 | try completed.applyFullText(data) |
| 838 | return completed |
| 839 | }.value |
| 840 | guard revision == accountRevision else { throw CompanionScheduleError.accountChanged } |
| 841 | syncedText = (incoming.workspaceID, version, data) |
| 842 | return completed |
| 843 | } |
| 844 | |
| 845 | func accountChanged() { |
| 846 | accountRevision = UUID() |
| 847 | clearSnapshot() |
| 848 | account = nil |
| 849 | accountStatus = "Not checked" |
| 850 | remoteWorkspaceFound = nil |
| 851 | lastCheck = nil |
| 852 | lastCloudContact = nil |
| 853 | syncErrorCode = nil |
| 854 | } |
| 855 | |
| 856 | #if DEBUG |
| 857 | private static var fixture: CompanionLibrary { |
| 858 | let fixtureID = ProcessInfo.processInfo.environment["INKSPRING_FIXTURE_ID"].flatMap(UUID.init(uuidString:)) |
| 859 | var value = CompanionLibrary(workspaceID: fixtureID ?? UUID(uuidString: "de6b0e64-2e7a-4bc6-a4b2-79a3e63b8e1a")!) |
| 860 | value.projects = [.init(id: "studio", name: "Studio")] |
| 861 | value.items = [ |
| 862 | .init(id: "draft", revision: "2026-11-16T12:00:00.000Z", kind: .draft, projectID: "studio", title: "A quieter way to draft", |
| 863 | body: "Start with the decision you made and why it mattered. One concrete example is enough.", |
| 864 | shortened: false, platform: "linkedin", status: "ready", notes: [], attachment: .video, referenceID: "STU-001"), |
| 865 | .init(id: "idea", revision: "2026-11-17T14:30:00Z", kind: .idea, projectID: "studio", title: "Show the unfinished work", |
| 866 | body: "Explain a trade-off from a work in progress and ask readers how they would handle it.", |
| 867 | shortened: false, platform: "", status: "draft", notes: []) |
| 868 | ] |
| 869 | if ProcessInfo.processInfo.arguments.contains("--review-timestamps-fixture") { |
| 870 | value.items += [ |
| 871 | .init(id: "newer-idea", revision: "2026-11-21T17:45:00.000Z", kind: .idea, projectID: "studio", |
| 872 | title: "Start with the smallest useful thing", body: "What could you build in one afternoon?", |
| 873 | shortened: false, platform: "", status: "picked", notes: []), |
| 874 | .init(id: "older-idea", revision: "legacy", kind: .idea, projectID: "studio", |
| 875 | title: "An idea from an older library", body: "Keep this idea visible without an invented update time.", |
| 876 | shortened: false, platform: "", status: "draft", notes: []) |
| 877 | ] |
| 878 | } |
| 879 | value.supportsRevisionWithdrawal = true |
| 880 | value.supportsDraftEdits = true |
| 881 | value.supportsNewsletterEdits = true |
| 882 | if ProcessInfo.processInfo.arguments.contains("--newsletter-offline-fixture") { |
| 883 | value.supportsNewsletterEdits = nil |
| 884 | } |
| 885 | value.supportsItemManagement = true |
| 886 | value.supportsXThreads = true |
| 887 | value.supportsXParagraphs = true |
| 888 | value.supportsAgentFeatures = !ProcessInfo.processInfo.arguments.contains("--no-mcp-fixture") |
| 889 | value.supportsRevisionHistory = true |
| 890 | value.supportsContentPlans = true |
| 891 | value.supportsClaudeIdeaDrafts = !ProcessInfo.processInfo.arguments.contains("--old-idea-draft-mac-fixture") |
| 892 | if ProcessInfo.processInfo.arguments.contains("--writing-model-fixture") { |
| 893 | value.writingAgent = "codex" |
| 894 | value.writingProviders = [ |
| 895 | .init(id: "claude", name: "Claude", defaultModel: "claude-sonnet-5-5", models: [ |
| 896 | .init(id: "claude-fable-5-2", name: "Fable 5.2"), .init(id: "claude-fable-5", name: "Fable 5"), |
| 897 | .init(id: "claude-sonnet-5-5", name: "Sonnet 5.5") |
| 898 | ]), |
| 899 | .init(id: "codex", name: "Codex", defaultModel: "gpt-6.2-sol", models: [ |
| 900 | .init(id: "gpt-6.2-astra", name: "GPT-6.2 Astra"), .init(id: "gpt-6.2-sol", name: "GPT-6.2 Sol"), |
| 901 | .init(id: "gpt-6.1-terra", name: "GPT-6.1 Terra") |
| 902 | ]) |
| 903 | ] |
| 904 | } |
| 905 | value.supportsMediaDrafts = true |
| 906 | if ProcessInfo.processInfo.arguments.contains("--post-images-fixture") { |
| 907 | let bytes = UIImage(systemName: "mountain.2.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 160))? |
| 908 | .withTintColor(.systemIndigo, renderingMode: .alwaysOriginal).pngData() |
| 909 | let draft = value.items[0] |
| 910 | value.items[0] = .init(id: draft.id, revision: draft.revision, kind: draft.kind, projectID: draft.projectID, |
| 911 | title: draft.title, body: draft.body, shortened: draft.shortened, |
| 912 | platform: draft.platform, status: draft.status, notes: draft.notes, |
| 913 | attachment: .image, referenceID: draft.referenceID) |
| 914 | value.items[0].imagePreview = bytes |
| 915 | if let bytes { value.additionalImagePreviews = ["fixture-1": bytes, "fixture-published": bytes] } |
| 916 | } |
| 917 | if ProcessInfo.processInfo.arguments.contains("--idea-image-fixture") { |
| 918 | value.supportsIdeaImages = true |
| 919 | value.ideaImageProvider = "OpenAI" |
| 920 | let idea = value.items[1] |
| 921 | var illustrated = CompanionLibrary.Item(id: idea.id, revision: idea.revision, kind: .idea, |
| 922 | projectID: idea.projectID, title: idea.title, body: idea.body, shortened: false, |
| 923 | platform: "", status: idea.status, notes: [], attachment: .image) |
| 924 | illustrated.imagePreview = UIImage(systemName: "photo.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 160))? |
| 925 | .withTintColor(.systemIndigo, renderingMode: .alwaysOriginal).pngData() |
| 926 | value.items[1] = illustrated |
| 927 | } |
| 928 | if ProcessInfo.processInfo.arguments.contains("--quick-x-fixture") { |
| 929 | value.supportsQuickXPost = true |
| 930 | value.xArticleAccountKey = "fixture:connected" |
| 931 | value.xArticleAccountName = "@fixture" |
| 932 | } |
| 933 | if ProcessInfo.processInfo.arguments.contains("--x-thread-fixture") { |
| 934 | var draft = CompanionLibrary.Item(id: "x-followup-demo", revision: "2026-11-18T16:00:00.000Z", kind: .draft, |
| 935 | projectID: "studio", title: "I opened the Lab", body: ["We build useful tools and give them away.", "Read more: https://newsletter.protomota.com/", "Join us: https://lab.protomota.com"].joined(separator: XThreadText.separator), |
| 936 | shortened: false, platform: "x", status: "draft", notes: [], referenceID: "STU-003") |
| 937 | if ProcessInfo.processInfo.arguments.contains("--article-link-fixture") { |
| 938 | value.supportsXReplyArticles = true |
| 939 | value.articles = [.init(id: "linked-article", revision: draft.revision, kind: .article, projectID: "studio", |
| 940 | title: "The manifesto", body: "# Our mission\n\nWe build useful tools together.", shortened: false, |
| 941 | platform: "x", status: "draft", notes: [], referenceID: "STU-004")] |
| 942 | var posts = XThreadText.posts(in: draft.body) |
| 943 | posts.insert(XReplyArticle.attach("STU-004", to: "Read the full manifesto on X."), at: 1) |
| 944 | draft.body = posts.joined(separator: XThreadText.separator) |
| 945 | } |
| 946 | draft.format = "thread" |
| 947 | value.items.insert(draft, at: 0) |
| 948 | } |
| 949 | if ProcessInfo.processInfo.arguments.contains("--script-fixture") { |
| 950 | value.supportsScripts = true |
| 951 | value.supportsWritingTools = true |
| 952 | value.supportsXArticlePublishing = true |
| 953 | value.xArticleAccountKey = "fixture:connected" |
| 954 | value.xArticleAccountName = "@fixture" |
| 955 | value.writingAgent = "codex" |
| 956 | value.scripts = [.init(id: "script-example", revision: "2026-11-19T12:00:00.000Z", kind: .script, |
| 957 | projectID: "studio", title: "I opened the Lab — YouTube script", |
| 958 | body: "We build real skills.\n\nWe protect our signal.\n\n" + String(repeating: "We learn by building and testing useful tools.\n\n", count: 50) + "End of the hallway script.", |
| 959 | shortened: false, platform: "youtube", status: "draft", notes: [], referenceID: "STU–003")] |
| 960 | } |
| 961 | if ProcessInfo.processInfo.arguments.contains("--newsletter-fixture") { |
| 962 | value.newsletters = [ |
| 963 | .init(id: "newsletter-draft", revision: "2026-11-16T12:00:00.000Z", kind: .newsletter, |
| 964 | projectID: "studio", title: "A better first paragraph", body: """ |
| 965 | ## Start with a detail |
| 966 | |
| 967 | Give the reader **one thing** they can picture. |
| 968 | |
| 969 | - Open with an example. |
| 970 | - Keep the first sentence short. |
| 971 | |
| 972 | [Visit Inkspring](https://inkspring.ai/) |
| 973 | """, |
| 974 | shortened: false, platform: "substack", status: "draft", notes: [], referenceID: "STU-002"), |
| 975 | .init(id: "newsletter-published", revision: "2026-11-15T12:00:00.000Z", kind: .newsletter, |
| 976 | projectID: "studio", title: "Notes from the studio", body: "What changed after a week of testing.", |
| 977 | shortened: false, platform: "substack", status: "published", notes: [], referenceID: "STU-003") |
| 978 | ] |
| 979 | } |
| 980 | if ProcessInfo.processInfo.arguments.contains("--existing-writing-fixture") { |
| 981 | let revision = "2026-11-19T12:00:00.000Z" |
| 982 | value.articles = [.init(id: "article-fixture", revision: revision, kind: .article, projectID: "studio", |
| 983 | title: "Untitled X article", body: "", shortened: false, platform: "x", status: "draft", notes: [])] |
| 984 | value.scripts = [.init(id: "script-fixture", revision: revision, kind: .script, projectID: "studio", |
| 985 | title: "Untitled YouTube script", body: "", shortened: false, platform: "youtube", status: "draft", notes: [])] |
| 986 | value.newsletters = [.init(id: "newsletter-fixture", revision: revision, kind: .newsletter, projectID: "studio", |
| 987 | title: "Untitled newsletter", body: "", shortened: false, platform: "substack", status: "draft", notes: [])] |
| 988 | } |
| 989 | if ProcessInfo.processInfo.arguments.contains("--project-filter-fixture") { |
| 990 | value.projects.append(.init(id: "field-notes", name: "Field Notes")) |
| 991 | value.items.append(.init(id: "field-draft", revision: "1", kind: .draft, projectID: "field-notes", |
| 992 | title: "What we learned in the field", body: "Lead with one example.", |
| 993 | shortened: false, platform: "linkedin", status: "draft", notes: [])) |
| 994 | value.newsletters?.append(.init(id: "field-newsletter", revision: "1", kind: .newsletter, projectID: "field-notes", |
| 995 | title: "A dispatch from the field", body: "One idea worth sharing.", |
| 996 | shortened: false, platform: "substack", status: "draft", notes: [])) |
| 997 | } |
| 998 | if ProcessInfo.processInfo.arguments.contains("--full-text-fixture") { |
| 999 | let paragraphs = String(repeating: "A complete paragraph stays in the library when contents sync through iCloud.\n\n", count: 126) |
| 1000 | value.items.append(.init(id: "full-post", revision: "1", kind: .draft, projectID: "studio", |
| 1001 | title: "Long post with complete text", body: paragraphs + "End of the complete post.", |
| 1002 | shortened: false, platform: "linkedin", status: "draft", notes: [])) |
| 1003 | value.newsletters = [.init(id: "full-newsletter", revision: "1", kind: .newsletter, projectID: "studio", |
| 1004 | title: "Long newsletter with complete text", body: paragraphs + "End of the complete newsletter.", |
| 1005 | shortened: false, platform: "substack", status: "draft", notes: [])] |
| 1006 | } |
| 1007 | value.postingWindows = ["linkedin": .init(), "reddit": .init()] |
| 1008 | value.postingTimeZone = TimeZone.current.identifier |
| 1009 | if ProcessInfo.processInfo.arguments.contains("--editing-fixture") { |
| 1010 | value.items.insert(.init(id: "long-draft", revision: "2026-11-15T12:00:00.000Z", kind: .draft, projectID: "studio", |
| 1011 | title: "I built a free AI transcription and notes app for Mac, iPhone and iPad that runs on-device with Apple Intelligence. No account, no subscription.", |
| 1012 | body: "I'm a solo developer, and I built Jotley for Mac, iPhone and iPad.\n\n" + String(repeating: "Your recordings, transcripts and notes stay on your device. Review the transcript, edit the summary and keep the details that matter.\n\n", count: 8), |
| 1013 | shortened: false, platform: "reddit", status: "draft", notes: [], attachment: .image), at: 0) |
| 1014 | var trashed = CompanionLibrary.Item(id: "trashed-example", revision: "1", kind: .draft, projectID: "studio", |
| 1015 | title: "What we changed after the first demo", |
| 1016 | body: "Our first PulseCanvas demo opened with the export settings. For the second cut, we started with eight bars of music so viewers could hear the beat and see the visual respond before we showed the controls.", |
| 1017 | shortened: false, platform: "linkedin", status: "draft", notes: ["Try a shorter introduction."]) |
| 1018 | trashed.isTrashed = true |
| 1019 | value.items.append(trashed) |
| 1020 | } |
| 1021 | return value |
| 1022 | } |
| 1023 | #endif |
| 1024 | } |
| 1025 | |
| 1026 | private struct MobileNewsletterDetail: View { |
| 1027 | @Environment(\.studioPalette) private var palette |
| 1028 | @Environment(\.scenePhase) private var scenePhase |
| 1029 | let item: CompanionLibrary.Item |
| 1030 | let metadata: String |
| 1031 | let library: MobileLibrary |
| 1032 | let workspaceID: UUID |
| 1033 | @State private var showsOutline = false |
| 1034 | @State private var editingRevision: String? |
| 1035 | @State private var editingBaseMarkdown = "" |
| 1036 | @State private var confirmsArticlePublication = false |
| 1037 | @State private var showsWritingTools = false |
| 1038 | @State private var scriptTitle = "" |
| 1039 | @State private var baseScriptTitle = "" |
| 1040 | @State private var findRequest = 0 |
| 1041 | @State private var markdown = "" |
| 1042 | @State private var saveError: String? |
| 1043 | @State private var showsMacVersion = false |
| 1044 | @State private var recoveryKey: String? |
| 1045 | |
| 1046 | private var pendingEdit: CompanionLibraryOutbox.Entry? { |
| 1047 | library.pendingChanges(for: item.id).last { $0.isLongFormEdit } |
| 1048 | } |
| 1049 | |
| 1050 | private var canEdit: Bool { |
| 1051 | !showsMacVersion && hasFullText && ["draft", "synced"].contains(item.status) |
| 1052 | } |
| 1053 | |
| 1054 | private var hasFullText: Bool { |
| 1055 | !item.shortened || (pendingEdit != nil && pendingEdit?.error == nil) |
| 1056 | } |
| 1057 | |
| 1058 | private var previewMarkdown: String { |
| 1059 | if let pendingEdit, pendingEdit.error == nil, !showsMacVersion { return pendingEdit.text } |
| 1060 | return item.body |
| 1061 | } |
| 1062 | |
| 1063 | var body: some View { |
| 1064 | if showsOutline { |
| 1065 | MobilePlanSection(item: item, library: library, workspaceID: workspaceID) { showsOutline = false } |
| 1066 | } else { |
| 1067 | document |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | private var document: some View { |
| 1072 | Group { |
| 1073 | if editingRevision != nil { |
| 1074 | VStack(alignment: .leading, spacing: 12) { |
| 1075 | if item.isLongForm { |
| 1076 | HStack(alignment: .top) { |
| 1077 | MobilePostImage(data: item.imagePreview, label: "Cover image", |
| 1078 | identifier: "writing.image.editor", thumbnail: true) |
| 1079 | TextField(item.kind == .newsletter ? "Newsletter title" : item.kind == .article ? "Article title" : "Script title", text: $scriptTitle) |
| 1080 | .textFieldStyle(.plain).font(.headline) |
| 1081 | .accessibilityIdentifier("script.title") |
| 1082 | } |
| 1083 | } |
| 1084 | MobileWritingTextView(text: $markdown, identifier: "newsletter.markdown", findRequest: findRequest, monospaced: true, onFocusLost: { save() }) |
| 1085 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 1086 | .studioSurface() |
| 1087 | if let saveError { |
| 1088 | VStack(alignment: .leading, spacing: 4) { |
| 1089 | Text(saveError).font(.footnote).foregroundStyle(palette.danger) |
| 1090 | Button("Copy unsaved Markdown", systemImage: "doc.on.doc") { |
| 1091 | UIPasteboard.general.string = markdown |
| 1092 | } |
| 1093 | } |
| 1094 | } |
| 1095 | } |
| 1096 | .padding(8) |
| 1097 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 1098 | } else { |
| 1099 | ScrollView { |
| 1100 | VStack(alignment: .leading, spacing: 16) { |
| 1101 | metadataHeader |
| 1102 | MobilePostImage(data: item.imagePreview, label: "Cover image", identifier: "writing.image.preview") |
| 1103 | if item.kind == .article, item.reviewPlatform == "x-article" { articlePublishing } |
| 1104 | Divider() |
| 1105 | if !hasFullText || (showsMacVersion && item.shortened) { |
| 1106 | Text("Waiting for the full text to sync.").font(.footnote).foregroundStyle(palette.muted) |
| 1107 | } else { |
| 1108 | Group { |
| 1109 | if previewMarkdown.isEmpty { |
| 1110 | Text(item.kind == .article ? "No article text yet. Double-tap to start writing." : item.kind == .script ? "No script text yet. Double-tap to start writing." : "No newsletter text yet.").foregroundStyle(palette.muted) |
| 1111 | } else { |
| 1112 | MobileNewsletterMarkdown(markdown: previewMarkdown).equatable() |
| 1113 | } |
| 1114 | } |
| 1115 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1116 | .contentShape(Rectangle()) |
| 1117 | .simultaneousGesture(TapGesture(count: 2).onEnded { beginEditing() }) |
| 1118 | } |
| 1119 | if !library.planText(item).isEmpty { |
| 1120 | Button("View outline", systemImage: "list.bullet.clipboard") { showsOutline = true } |
| 1121 | .font(.callout) |
| 1122 | .accessibilityIdentifier("outline.view") |
| 1123 | } |
| 1124 | if let pendingEdit { |
| 1125 | if let error = pendingEdit.error { |
| 1126 | Text(error).font(.footnote).foregroundStyle(palette.danger) |
| 1127 | Button("Copy unsynced Markdown", systemImage: "doc.on.doc") { |
| 1128 | UIPasteboard.general.string = pendingEdit.text |
| 1129 | } |
| 1130 | } else { |
| 1131 | let status = library.newsletterSyncStatus(for: pendingEdit) |
| 1132 | Text(syncMessage(status)).font(.footnote).foregroundStyle(palette.muted) |
| 1133 | if pendingEdit.revision != item.revision && !item.shortened { |
| 1134 | Button(showsMacVersion ? "Show saved mobile edit" : "Show version from Mac") { |
| 1135 | showsMacVersion.toggle() |
| 1136 | } |
| 1137 | } |
| 1138 | } |
| 1139 | } |
| 1140 | } |
| 1141 | .padding(16) |
| 1142 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1143 | .studioSurface() |
| 1144 | .padding(16) |
| 1145 | .frame(maxWidth: 760) |
| 1146 | .frame(maxWidth: .infinity) |
| 1147 | } |
| 1148 | .accessibilityIdentifier("newsletter.preview") |
| 1149 | } |
| 1150 | } |
| 1151 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 1152 | .tint(palette.iconAccent) |
| 1153 | .toolbar(editingRevision == nil ? .visible : .hidden, for: .tabBar) |
| 1154 | .navigationTitle(item.kind == .newsletter ? "Newsletter" : reviewPlatformName(item.reviewPlatform == "youtube" ? "youtube-script" : item.reviewPlatform)) |
| 1155 | .navigationBarTitleDisplayMode(.inline) |
| 1156 | .onChange(of: markdown + "\0" + scriptTitle) { |
| 1157 | guard let editingRevision, let recoveryKey, markdown != editingBaseMarkdown || scriptTitle != baseScriptTitle else { return } |
| 1158 | library.storeNewsletterRecovery(.init(revision: editingRevision, base: editingBaseMarkdown, markdown: markdown, title: scriptTitle, baseTitle: baseScriptTitle), |
| 1159 | key: recoveryKey) |
| 1160 | } |
| 1161 | .task(id: markdown + "\0" + scriptTitle) { |
| 1162 | guard editingRevision != nil, markdown != editingBaseMarkdown || scriptTitle != baseScriptTitle else { return } |
| 1163 | do { try await Task.sleep(for: .milliseconds(750)) } |
| 1164 | catch { return } |
| 1165 | save() |
| 1166 | } |
| 1167 | .onChange(of: scenePhase) { _, phase in |
| 1168 | if phase != .active { save() } |
| 1169 | } |
| 1170 | .onDisappear { save() } |
| 1171 | .onChange(of: item.revision) { |
| 1172 | guard editingRevision != nil, markdown == editingBaseMarkdown, scriptTitle == baseScriptTitle, pendingEdit == nil, |
| 1173 | item.revisionDate != nil else { return } |
| 1174 | markdown = item.body |
| 1175 | editingBaseMarkdown = item.body |
| 1176 | scriptTitle = item.title |
| 1177 | baseScriptTitle = item.title |
| 1178 | editingRevision = item.revision |
| 1179 | } |
| 1180 | .onChange(of: pendingEdit?.id) { |
| 1181 | if pendingEdit == nil { showsMacVersion = false } |
| 1182 | } |
| 1183 | .toolbar { |
| 1184 | ToolbarItemGroup(placement: .topBarTrailing) { |
| 1185 | if editingRevision != nil { |
| 1186 | Button("Find", systemImage: "magnifyingglass") { findRequest += 1 } |
| 1187 | .accessibilityIdentifier("editor.find") |
| 1188 | if library.canUseAgentFeatures { |
| 1189 | MobileWritingTools(title: $scriptTitle, text: $markdown, presented: $showsWritingTools, |
| 1190 | agent: library.snapshot?.writingAgent ?? "agent", providers: library.snapshot?.writingProviders, |
| 1191 | requests: writingRequests, reply: item.writingReply, error: item.writingError) { prompt, selection in |
| 1192 | save() |
| 1193 | guard saveError == nil else { throw CompanionLibraryError.invalid } |
| 1194 | var change = CompanionLibrary.Change(action: .note, itemID: item.id, revision: editingRevision ?? item.revision, |
| 1195 | text: prompt, requestsWritingHelp: true) |
| 1196 | change.writingSelection = selection |
| 1197 | try library.saveChange(change, workspaceID: workspaceID) |
| 1198 | } |
| 1199 | } |
| 1200 | Button("Done") { save(ending: true) }.fontWeight(.semibold) |
| 1201 | } else { |
| 1202 | Menu { |
| 1203 | if ["draft", "synced"].contains(item.status) { |
| 1204 | Button("Edit Markdown", systemImage: "pencil", action: beginEditing).disabled(!canEdit) |
| 1205 | if library.canUseAgentFeatures { |
| 1206 | Button("Ask AI…", systemImage: "bubble.left.and.text.bubble.right") { beginEditing(); showsWritingTools = true }.disabled(!canEdit) |
| 1207 | } |
| 1208 | } |
| 1209 | if library.snapshot?.supportsContentPlans == true && item.isTrashed != true { |
| 1210 | Button(library.planText(item).isEmpty ? "Add outline" : "View outline", systemImage: "list.bullet.clipboard") { showsOutline = true } |
| 1211 | .accessibilityIdentifier("outline.menu") |
| 1212 | } |
| 1213 | Button("Copy Markdown", systemImage: "doc.on.doc") { UIPasteboard.general.string = previewMarkdown } |
| 1214 | .disabled(!hasFullText || previewMarkdown.isEmpty) |
| 1215 | } label: { |
| 1216 | Label("More", systemImage: "ellipsis.circle") |
| 1217 | } |
| 1218 | .accessibilityIdentifier("newsletter.more") |
| 1219 | } |
| 1220 | } |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | private var articlePublishing: some View { |
| 1225 | VStack(alignment: .leading, spacing: 10) { |
| 1226 | if let raw = item.publicationURL, let url = URL(string: raw), url.scheme == "https", url.host == "x.com" { |
| 1227 | Link("View published X article", destination: url) |
| 1228 | } else if item.status == "published" || item.status == "uncertain" || item.status == "publishing" { |
| 1229 | Text(item.status == "uncertain" ? "X hasn’t confirmed publication. Check X Articles on your Mac before retrying." : "Publishing to X…") |
| 1230 | .font(.footnote) |
| 1231 | } else if library.pendingChanges(for: item.id).contains(where: { $0.publishesXArticle == true }) || item.publicationStatus == "queued" { |
| 1232 | Text("Publishing request saved. Your Mac will publish while Inkspring is open.").font(.footnote) |
| 1233 | } else { |
| 1234 | Button("Review & publish on X…", systemImage: "paperplane") { confirmsArticlePublication = true } |
| 1235 | .disabled(!hasFullText || item.body.isEmpty || pendingEdit != nil || library.snapshot?.supportsXArticlePublishing != true || library.snapshot?.xArticleAccountKey == nil) |
| 1236 | .accessibilityIdentifier("article.reviewPublish") |
| 1237 | Text(library.snapshot?.xArticleAccountKey == nil ? "Connect X in Inkspring on your Mac to publish Articles." : "Your Mac publishes the full article to X while Inkspring is open. Requires X Article access and API credits.") |
| 1238 | .font(.footnote).foregroundStyle(palette.muted) |
| 1239 | } |
| 1240 | if let error = item.publicationError, !error.isEmpty { Text(error).font(.footnote).foregroundStyle(palette.muted) } |
| 1241 | } |
| 1242 | .confirmationDialog("Publish this X article?", isPresented: $confirmsArticlePublication, titleVisibility: .visible) { |
| 1243 | Button("Publish article now") { |
| 1244 | do { |
| 1245 | try library.saveChange(.init(action: .note, itemID: item.id, revision: item.revision, |
| 1246 | text: "Publish X article", publishesXArticle: true, xArticleAccountKey: library.snapshot?.xArticleAccountKey), workspaceID: workspaceID) |
| 1247 | } catch { saveError = error.localizedDescription } |
| 1248 | }.accessibilityIdentifier("article.publish") |
| 1249 | } message: { |
| 1250 | Text("Publish “\(item.title)” publicly as \(library.snapshot?.xArticleAccountName ?? "your connected X account")? Your Mac must be awake with Inkspring open.") |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | private var writingRequests: [StudioWritingRequest] { |
| 1255 | library.revisionRequests(for: item) |
| 1256 | } |
| 1257 | |
| 1258 | private func syncMessage(_ status: MobileLibrary.NewsletterSyncStatus) -> String { |
| 1259 | switch status { |
| 1260 | case .needsMacUpdate: "Saved on this device. Open the latest Inkspring on your Mac to sync this edit." |
| 1261 | case .waitingForMac: "Sent to iCloud. Waiting for Inkspring on your Mac to apply the edit." |
| 1262 | case .savedOnDevice: "Saved on this device. Waiting to upload to iCloud." |
| 1263 | case .needsReview: "Your mobile edit is saved on this device." |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | private var metadataHeader: some View { |
| 1268 | VStack(alignment: .leading, spacing: 7) { |
| 1269 | Text(item.isLongForm && pendingEdit?.title.isEmpty == false || pendingEdit?.restoresRevision == true ? pendingEdit?.title ?? item.title : item.title) |
| 1270 | .font(.title2.bold()).accessibilityAddTraits(.isHeader) |
| 1271 | HStack(alignment: .firstTextBaseline, spacing: 6) { |
| 1272 | StudioPlatformLabel(name: item.platform, title: reviewPlatformName(item.reviewPlatform)) |
| 1273 | Text("·").accessibilityHidden(true) |
| 1274 | Text(metadata) |
| 1275 | } |
| 1276 | .font(.footnote) |
| 1277 | .foregroundStyle(palette.muted) |
| 1278 | if let reference = item.referenceID { |
| 1279 | StudioCopyReference(reference: reference) |
| 1280 | } |
| 1281 | if let updatedAt = library.lastUpdated(item) { |
| 1282 | Text("Last updated \(updatedAt.formatted(date: .abbreviated, time: .standard))") |
| 1283 | .font(.footnote) |
| 1284 | .foregroundStyle(palette.muted) |
| 1285 | .accessibilityIdentifier("newsletter.lastUpdated") |
| 1286 | } |
| 1287 | NavigationLink { |
| 1288 | MobileRevisionHistory(item: item, library: library, workspaceID: workspaceID) |
| 1289 | } label: { Label("Revision history", systemImage: "clock.arrow.circlepath") } |
| 1290 | .accessibilityIdentifier("history.open") |
| 1291 | } |
| 1292 | .foregroundStyle(palette.text) |
| 1293 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1294 | } |
| 1295 | |
| 1296 | private func beginEditing() { |
| 1297 | guard canEdit, editingRevision == nil else { return } |
| 1298 | recoveryKey = library.newsletterRecoveryKey(for: item.id, workspaceID: workspaceID) |
| 1299 | let recovery = recoveryKey.flatMap { library.recoverNewsletterEdit(key: $0) } |
| 1300 | editingBaseMarkdown = recovery?.base ?? previewMarkdown |
| 1301 | markdown = recovery?.markdown ?? editingBaseMarkdown |
| 1302 | scriptTitle = recovery?.title ?? (pendingEdit?.title.isEmpty == false ? pendingEdit?.title ?? item.title : item.title) |
| 1303 | baseScriptTitle = recovery?.baseTitle ?? (pendingEdit?.title.isEmpty == false ? pendingEdit?.title ?? item.title : item.title) |
| 1304 | editingRevision = recovery?.revision ?? item.revision |
| 1305 | } |
| 1306 | |
| 1307 | private func endEditing() { |
| 1308 | editingRevision = nil |
| 1309 | saveError = nil |
| 1310 | recoveryKey = nil |
| 1311 | } |
| 1312 | |
| 1313 | private func save(ending: Bool = false) { |
| 1314 | guard let editingRevision else { return } |
| 1315 | if markdown == editingBaseMarkdown && scriptTitle == baseScriptTitle { |
| 1316 | if let recoveryKey { library.storeNewsletterRecovery(nil, key: recoveryKey) } |
| 1317 | if ending { endEditing() } |
| 1318 | return |
| 1319 | } |
| 1320 | do { |
| 1321 | var edit = CompanionLibrary.Change(action: .editDraft, itemID: item.id, revision: editingRevision, title: [.script, .article].contains(item.kind) || scriptTitle != baseScriptTitle ? scriptTitle : "", |
| 1322 | text: markdown, editsNewsletter: item.kind == .newsletter ? true : nil, baseNewsletterText: editingBaseMarkdown, editsScript: [.script, .article].contains(item.kind) ? true : nil, baseScriptTitle: [.script, .article].contains(item.kind) || scriptTitle != baseScriptTitle ? baseScriptTitle : nil, writingKind: item.kind == .article ? "article" : nil) |
| 1323 | if !edit.valid || (try? JSONEncoder().encode(edit).count).map({ $0 > edit.payloadLimit }) == true { |
| 1324 | edit = .init(id: edit.id, action: edit.action, itemID: edit.itemID, revision: edit.revision, title: edit.title, |
| 1325 | text: edit.text, editsNewsletter: item.kind == .newsletter ? true : nil, editsScript: [.script, .article].contains(item.kind) ? true : nil, baseScriptTitle: [.script, .article].contains(item.kind) || scriptTitle != baseScriptTitle ? baseScriptTitle : nil, writingKind: item.kind == .article ? "article" : nil) |
| 1326 | } |
| 1327 | try library.saveChange(edit, workspaceID: workspaceID) |
| 1328 | showsMacVersion = false |
| 1329 | editingBaseMarkdown = markdown |
| 1330 | baseScriptTitle = scriptTitle |
| 1331 | if let recoveryKey { library.storeNewsletterRecovery(nil, key: recoveryKey) } |
| 1332 | saveError = nil |
| 1333 | if ending { endEditing() } |
| 1334 | } catch { |
| 1335 | saveError = error.localizedDescription |
| 1336 | } |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | private struct MobileNewsletterMarkdown: View, Equatable { |
| 1341 | @Environment(\.studioPalette) private var palette |
| 1342 | let markdown: String |
| 1343 | |
| 1344 | nonisolated static func == (lhs: Self, rhs: Self) -> Bool { lhs.markdown == rhs.markdown } |
| 1345 | |
| 1346 | private struct Block: Identifiable { |
| 1347 | let id: Int |
| 1348 | let kind: PresentationIntent.Kind |
| 1349 | let quote: Bool |
| 1350 | let listDepth: Int |
| 1351 | let marker: String? |
| 1352 | var text: AttributedString |
| 1353 | } |
| 1354 | |
| 1355 | var body: some View { |
| 1356 | VStack(alignment: .leading, spacing: 12) { |
| 1357 | ForEach(Self.parse(markdown)) { block in |
| 1358 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 1359 | if let marker = block.marker { |
| 1360 | Text(marker).foregroundStyle(palette.muted).accessibilityHidden(true) |
| 1361 | } |
| 1362 | blockContent(block) |
| 1363 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1364 | } |
| 1365 | .padding(.leading, CGFloat(block.listDepth) * 16 + (block.quote ? 12 : 0)) |
| 1366 | .overlay(alignment: .leading) { |
| 1367 | if block.quote { Rectangle().fill(palette.line).frame(width: 2) } |
| 1368 | } |
| 1369 | } |
| 1370 | } |
| 1371 | .foregroundStyle(palette.text) |
| 1372 | } |
| 1373 | |
| 1374 | @ViewBuilder private func blockContent(_ block: Block) -> some View { |
| 1375 | switch block.kind { |
| 1376 | case .header(let level): |
| 1377 | Text(block.text) |
| 1378 | .font((level == 1 ? Font.title : level == 2 ? .title2 : .headline).bold()) |
| 1379 | .accessibilityAddTraits(.isHeader) |
| 1380 | case .codeBlock: |
| 1381 | Text(block.text).font(.system(.callout, design: .monospaced)) |
| 1382 | .padding(10).studioSurface(StudioRadius.control, fill: palette.well) |
| 1383 | case .thematicBreak: |
| 1384 | Divider() |
| 1385 | default: |
| 1386 | Text(block.text).font(.body) |
| 1387 | } |
| 1388 | } |
| 1389 | |
| 1390 | private static func parse(_ markdown: String) -> [Block] { |
| 1391 | guard let attributed = try? AttributedString(markdown: markdown, options: .init(failurePolicy: .returnPartiallyParsedIfPossible)) else { |
| 1392 | return [.init(id: 0, kind: .paragraph, quote: false, listDepth: 0, marker: nil, text: AttributedString(markdown))] |
| 1393 | } |
| 1394 | var result: [Block] = [] |
| 1395 | var seenListItems: Set<Int> = [] |
| 1396 | for run in attributed.runs { |
| 1397 | let components = run.presentationIntent?.components ?? [] |
| 1398 | let id = components.first?.identity ?? 0 |
| 1399 | var text = AttributedString(attributed[run.range]) |
| 1400 | text.presentationIntent = nil |
| 1401 | if let url = run.link { |
| 1402 | if ["http", "https", "mailto"].contains(url.scheme?.lowercased() ?? "") { |
| 1403 | text.underlineStyle = .single |
| 1404 | } else { |
| 1405 | text.link = nil |
| 1406 | } |
| 1407 | } |
| 1408 | if run.inlinePresentationIntent?.contains(.code) == true { text.font = .system(.body, design: .monospaced) } |
| 1409 | if result.last?.id == id { |
| 1410 | result[result.count - 1].text.append(text) |
| 1411 | continue |
| 1412 | } |
| 1413 | let quote = components.contains { $0.kind == .blockQuote } |
| 1414 | let listDepth = components.count { $0.kind == .orderedList || $0.kind == .unorderedList } |
| 1415 | let listPosition = components.firstIndex { if case .listItem = $0.kind { true } else { false } } |
| 1416 | var marker: String? |
| 1417 | if let listPosition, case .listItem(let ordinal) = components[listPosition].kind, |
| 1418 | seenListItems.insert(components[listPosition].identity).inserted { |
| 1419 | marker = components.dropFirst(listPosition + 1).first?.kind == .orderedList ? "\(ordinal)." : "•" |
| 1420 | } |
| 1421 | result.append(.init(id: id, kind: components.first?.kind ?? .paragraph, quote: quote, |
| 1422 | listDepth: max(0, listDepth - (marker == nil ? 0 : 1)), marker: marker, text: text)) |
| 1423 | } |
| 1424 | return result |
| 1425 | } |
| 1426 | } |
| 1427 | |
| 1428 | struct MobileReviewView: View { |
| 1429 | @Environment(\.mobileWideLayout) private var wideLayout |
| 1430 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 1431 | let library: MobileLibrary |
| 1432 | let isSelected: Bool |
| 1433 | let writeIdea: () -> Void |
| 1434 | let openSetup: () -> Void |
| 1435 | let openSettings: () -> Void |
| 1436 | @Environment(\.studioPalette) private var palette |
| 1437 | @State private var selection: String? |
| 1438 | @State private var compactColumn: NavigationSplitViewColumn = .sidebar |
| 1439 | @State private var filter = "Drafts" |
| 1440 | @State private var platformFilter: String? |
| 1441 | @State private var projectFilter: String? |
| 1442 | @AppStorage("inkspring.mobile.draftSort") private var draftSort = DraftSort.lastUpdated |
| 1443 | @State private var editItem: CompanionLibrary.Item? |
| 1444 | @State private var deleteItem: CompanionLibrary.Item? |
| 1445 | @State private var actionError: String? |
| 1446 | @State private var draftingIdea = false |
| 1447 | @State private var quickXPost = false |
| 1448 | @State private var askingInkspring = false |
| 1449 | |
| 1450 | private static let filters = ["Drafts", "Ideas", "Trash"] |
| 1451 | |
| 1452 | private enum DraftSort: String, CaseIterable { |
| 1453 | case lastUpdated = "Last updated" |
| 1454 | case oldestUpdate = "Oldest update" |
| 1455 | case title = "Title A–Z" |
| 1456 | |
| 1457 | func sorted(_ items: [CompanionLibrary.Item], updatedAt: (CompanionLibrary.Item) -> Date?) -> [CompanionLibrary.Item] { |
| 1458 | if self == .title { |
| 1459 | return items.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } |
| 1460 | } |
| 1461 | return items.map { (item: $0, date: updatedAt($0)) } |
| 1462 | .sorted { lhs, rhs in |
| 1463 | guard let lhsDate = lhs.date else { return false } |
| 1464 | guard let rhsDate = rhs.date else { return true } |
| 1465 | return self == .lastUpdated ? lhsDate > rhsDate : lhsDate < rhsDate |
| 1466 | } |
| 1467 | .map(\.item) |
| 1468 | } |
| 1469 | } |
| 1470 | |
| 1471 | private var drafts: [CompanionLibrary.Item] { |
| 1472 | let posts = library.visibleItems.filter { $0.kind == .draft && $0.isTrashed != true } |
| 1473 | return (posts + (library.snapshot?.newsletters ?? []) + library.visibleScripts).filter { |
| 1474 | $0.status != "published" && $0.status != "posted" |
| 1475 | && ($0.kind != .article || ($0.publicationURL ?? "").isEmpty) |
| 1476 | } |
| 1477 | } |
| 1478 | |
| 1479 | private var platformOptions: [String] { |
| 1480 | var platforms = Set(drafts.map(\.reviewPlatform).filter { !$0.isEmpty }) |
| 1481 | platforms.insert("substack") |
| 1482 | platforms.insert("youtube") |
| 1483 | platforms.insert("x-article") |
| 1484 | if let platformFilter { platforms.insert(platformFilter) } |
| 1485 | return platforms.sorted { reviewPlatformName($0).localizedStandardCompare(reviewPlatformName($1)) == .orderedAscending } |
| 1486 | } |
| 1487 | |
| 1488 | private var projectOptions: [CompanionLibrary.Project] { |
| 1489 | (library.snapshot?.projects ?? []).sorted { |
| 1490 | $0.name.localizedStandardCompare($1.name) == .orderedAscending |
| 1491 | } |
| 1492 | } |
| 1493 | |
| 1494 | private var items: [CompanionLibrary.Item] { |
| 1495 | switch filter { |
| 1496 | case "Drafts": |
| 1497 | return draftSort.sorted(drafts.filter { item in |
| 1498 | (projectFilter == nil || item.projectID == projectFilter) && |
| 1499 | (platformFilter == nil || item.reviewPlatform == platformFilter) |
| 1500 | }, updatedAt: library.lastUpdated) |
| 1501 | case "Trash": |
| 1502 | return DraftSort.lastUpdated.sorted(library.visibleItems.filter { $0.isTrashed == true }, updatedAt: library.lastUpdated) |
| 1503 | default: |
| 1504 | return DraftSort.lastUpdated.sorted(library.visibleItems.filter { $0.isTrashed != true && $0.kind == .idea }, |
| 1505 | updatedAt: library.lastUpdated) |
| 1506 | } |
| 1507 | } |
| 1508 | |
| 1509 | private var emptyMessage: String { |
| 1510 | if filter == "Trash" { return "Trash is empty." } |
| 1511 | if filter == "Drafts", platformFilter == "substack" { |
| 1512 | if library.snapshot?.newsletters == nil { return "Update Inkspring on your Mac to sync newsletters." } |
| 1513 | return projectFilter == nil ? "No Substack newsletters in your workspace." : "No Substack newsletters in this project." |
| 1514 | } |
| 1515 | if filter == "Drafts", projectFilter != nil { return "No matching drafts in this project." } |
| 1516 | if filter == "Drafts", let platformFilter { return "No \(reviewPlatformName(platformFilter)) drafts to review." } |
| 1517 | return "No \(filter.lowercased()) to review." |
| 1518 | } |
| 1519 | |
| 1520 | var body: some View { |
| 1521 | if library.snapshot == nil { |
| 1522 | NavigationStack { |
| 1523 | ScrollView { |
| 1524 | VStack(alignment: .leading, spacing: 16) { |
| 1525 | Image(systemName: "tray").font(.largeTitle).foregroundStyle(palette.iconAccent) |
| 1526 | Text("Your writing workspace").font(.title2.bold()) |
| 1527 | Text("Your drafts will appear here when your Mac library syncs. In the meantime, you can save ideas on this device.") |
| 1528 | .foregroundStyle(palette.muted) |
| 1529 | Button("Write an idea", systemImage: "square.and.pencil", action: writeIdea) |
| 1530 | .buttonStyle(MobilePrimaryActionStyle(fillsWidth: false)) |
| 1531 | Button("Mac setup guide", systemImage: "desktopcomputer", action: openSetup) |
| 1532 | Button("Check sync in Settings", systemImage: "icloud", action: openSettings) |
| 1533 | }.frame(maxWidth: 480, alignment: .leading).padding(24) |
| 1534 | .frame(maxWidth: .infinity, alignment: .center) |
| 1535 | }.mobileCanvas().mobilePageTitle("Review", wide: wideLayout, background: palette.canvas) |
| 1536 | .toolbar(wideLayout ? .hidden : .visible, for: .tabBar) |
| 1537 | } |
| 1538 | } else if askingInkspring { assistantView } |
| 1539 | else { |
| 1540 | reviewWithIdeaComposer |
| 1541 | .sheet(isPresented: $quickXPost) { |
| 1542 | NavigationStack { MobileQuickXComposer(library: library, preferredProject: projectFilter) } |
| 1543 | } |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | @ViewBuilder private var reviewWithIdeaComposer: some View { |
| 1548 | if wideLayout { |
| 1549 | reviewBody.fullScreenCover(isPresented: $draftingIdea, onDismiss: showCreatedIdea) { newIdeaComposer } |
| 1550 | } else { |
| 1551 | reviewBody.sheet(isPresented: $draftingIdea, onDismiss: showCreatedIdea) { newIdeaComposer } |
| 1552 | } |
| 1553 | } |
| 1554 | |
| 1555 | private var newIdeaComposer: some View { |
| 1556 | MobileIdeasView(library: library, isSelected: true, initialProject: projectFilter) { id in |
| 1557 | newIdeaID = id |
| 1558 | draftingIdea = false |
| 1559 | } |
| 1560 | } |
| 1561 | |
| 1562 | private var assistantView: some View { |
| 1563 | InkspringAssistantChat(workspaceID: library.planRecoveryID("assistant", workspaceID: library.snapshot?.workspaceID ?? UUID()), |
| 1564 | items: { library.assistantContents }, execute: library.executeAssistant, |
| 1565 | open: { id in selection = id; askingInkspring = false }, back: { askingInkspring = false }, |
| 1566 | readPlan: { id in |
| 1567 | guard let item = ((library.snapshot?.items ?? []) + (library.snapshot?.newsletters ?? [])).first(where: { $0.id == id }) else { return nil } |
| 1568 | return library.planText(item) |
| 1569 | }, applyPlan: { id, text, base in |
| 1570 | guard let snapshot = library.snapshot, |
| 1571 | let item = (snapshot.items + (snapshot.newsletters ?? [])).first(where: { $0.id == id }) else { throw CompanionScheduleError.changed } |
| 1572 | try library.savePlan(text, base: base, item: item, workspaceID: snapshot.workspaceID) |
| 1573 | return .init(message: "Plan saved on this device. Waiting for your Mac to apply it.", itemID: id) |
| 1574 | }) |
| 1575 | } |
| 1576 | |
| 1577 | private var reviewBody: some View { |
| 1578 | NavigationSplitView(preferredCompactColumn: $compactColumn) { |
| 1579 | Group { |
| 1580 | if let snapshot = library.snapshot { |
| 1581 | List(selection: $selection) { |
| 1582 | Section { |
| 1583 | VStack(alignment: .leading, spacing: 10) { |
| 1584 | reviewFilters |
| 1585 | if filter == "Drafts" { draftFilters } |
| 1586 | } |
| 1587 | .listRowBackground(Color.clear) |
| 1588 | } |
| 1589 | Section { |
| 1590 | if filter == "Drafts" { |
| 1591 | ForEach(library.pendingQuickXPosts) { request in |
| 1592 | VStack(alignment: .leading, spacing: 4) { |
| 1593 | Label(request.error ?? "Quick X post queued for your Mac.", |
| 1594 | systemImage: request.error == nil ? "clock" : "exclamationmark.icloud") |
| 1595 | MobileLastUpdated(date: request.savedAt) |
| 1596 | } |
| 1597 | .font(.footnote) |
| 1598 | .listRowBackground(palette.card) |
| 1599 | } |
| 1600 | ForEach(library.pendingMediaDrafts) { request in |
| 1601 | if let media = request.mediaDraft, (projectFilter == nil || request.itemID == projectFilter), |
| 1602 | (platformFilter == nil || media.platform == platformFilter) { |
| 1603 | VStack(alignment: .leading, spacing: 4) { |
| 1604 | Label(request.error ?? "\(reviewPlatformName(media.platform)) draft queued for your Mac.", |
| 1605 | systemImage: request.error == nil ? "clock" : "exclamationmark.icloud") |
| 1606 | MobileLastUpdated(date: request.savedAt) |
| 1607 | } |
| 1608 | .font(.footnote) |
| 1609 | .listRowBackground(palette.card) |
| 1610 | } |
| 1611 | } |
| 1612 | } |
| 1613 | if items.isEmpty { |
| 1614 | Text(emptyMessage) |
| 1615 | .foregroundStyle(.secondary) |
| 1616 | .listRowBackground(palette.card) |
| 1617 | } |
| 1618 | ForEach(items) { item in reviewRow(item, in: snapshot) } |
| 1619 | if filter == "Drafts", platformFilter == "substack", snapshot.hasMoreNewsletters == true { |
| 1620 | Text("Open Inkspring on Mac to see the rest of your newsletters.") |
| 1621 | .font(.footnote).foregroundStyle(palette.muted) |
| 1622 | } |
| 1623 | } |
| 1624 | .listRowBackground(palette.card) |
| 1625 | } |
| 1626 | .listStyle(.insetGrouped) |
| 1627 | .scrollContentBackground(.hidden) |
| 1628 | .listSectionSpacing(.compact) |
| 1629 | |
| 1630 | } |
| 1631 | } |
| 1632 | .mobileCanvas() |
| 1633 | .navigationTitle("Review") |
| 1634 | .navigationBarTitleDisplayMode(wideLayout ? .inline : .automatic) |
| 1635 | .toolbar(wideLayout ? .hidden : .visible, for: .tabBar) |
| 1636 | .refreshable { await library.refresh() } |
| 1637 | .toolbar { |
| 1638 | ideaToolbarItem |
| 1639 | ToolbarItem(placement: .topBarTrailing) { |
| 1640 | Button { askingInkspring = true } label: { |
| 1641 | Label("Ask Inkspring", systemImage: "sparkles").labelStyle(.titleAndIcon) |
| 1642 | } |
| 1643 | .accessibilityIdentifier("assistant.open") |
| 1644 | } |
| 1645 | ToolbarItem(placement: .topBarTrailing) { |
| 1646 | Button { quickXPost = true } label: { |
| 1647 | PlatformMark(name: "x", fallback: "paperplane").frame(width: 18, height: 18) |
| 1648 | } |
| 1649 | .accessibilityLabel("Quick X post") |
| 1650 | .accessibilityIdentifier("quickX.open") |
| 1651 | } |
| 1652 | ToolbarItem(placement: .topBarTrailing) { |
| 1653 | Button("Refresh", systemImage: "arrow.clockwise") { Task { await library.refresh() } } |
| 1654 | .disabled(library.busy) |
| 1655 | } |
| 1656 | } |
| 1657 | } detail: { |
| 1658 | Group { |
| 1659 | if let snapshot = library.snapshot, let item = items.first(where: { $0.id == selection }) { |
| 1660 | if item.isLongForm { |
| 1661 | MobileNewsletterDetail(item: item, metadata: [projectName(item, in: snapshot), status(item)] |
| 1662 | .joined(separator: " · "), library: library, workspaceID: snapshot.workspaceID) |
| 1663 | .id("\(snapshot.workspaceID)-\(item.id)") |
| 1664 | } else { |
| 1665 | MobileReviewDetail(item: item, library: library, workspaceID: snapshot.workspaceID) |
| 1666 | .id("\(snapshot.workspaceID)-\(item.id)") |
| 1667 | } |
| 1668 | } else if library.snapshot != nil && items.isEmpty { |
| 1669 | if filter == "Trash" { |
| 1670 | ContentUnavailableView("Trash is empty", systemImage: "trash") |
| 1671 | } else { |
| 1672 | ContentUnavailableView(emptyMessage, systemImage: "doc.text") |
| 1673 | } |
| 1674 | } else { |
| 1675 | Color.clear |
| 1676 | } |
| 1677 | } |
| 1678 | .mobileCanvas() |
| 1679 | } |
| 1680 | .onChange(of: items.map(\.id), initial: true) { _, _ in updateSelection() } |
| 1681 | .onChange(of: wideLayout) { _, _ in updateSelection() } |
| 1682 | .onChange(of: library.snapshot?.workspaceID) { _, _ in projectFilter = nil } |
| 1683 | .onChange(of: projectOptions.map(\.id)) { _, ids in |
| 1684 | if let projectFilter, !ids.contains(projectFilter) { self.projectFilter = nil } |
| 1685 | } |
| 1686 | .navigationDestination(isPresented: Binding(get: { editItem != nil }, set: { if !$0 { editItem = nil } })) { |
| 1687 | if let item = editItem, let snapshot = library.snapshot { |
| 1688 | MobileItemEditor(item: item, library: library, workspaceID: snapshot.workspaceID) |
| 1689 | } |
| 1690 | } |
| 1691 | .modifier(MobilePermanentDeletionConfirmation( |
| 1692 | isPresented: Binding(get: { deleteItem != nil }, set: { if !$0 { deleteItem = nil } }), |
| 1693 | message: "This cannot be undone. Linked posts and media files are kept.", |
| 1694 | remove: removeSelectedItem |
| 1695 | )) |
| 1696 | .alert("Couldn't save the change", isPresented: Binding(get: { actionError != nil }, set: { if !$0 { actionError = nil } })) { |
| 1697 | Button("OK", role: .cancel) { actionError = nil } |
| 1698 | } message: { Text(actionError ?? "") } |
| 1699 | .modifier(InkspringRatingPrompt(isIdle: isSelected && selection == nil && !library.busy && library.snapshot != nil)) |
| 1700 | } |
| 1701 | |
| 1702 | private var draftFilters: some View { |
| 1703 | let layout = dynamicTypeSize.isAccessibilitySize |
| 1704 | ? AnyLayout(VStackLayout(alignment: .leading, spacing: 0)) |
| 1705 | : AnyLayout(HStackLayout(spacing: wideLayout ? 6 : 8)) |
| 1706 | return layout { |
| 1707 | platformMenu |
| 1708 | projectMenu |
| 1709 | sortMenu |
| 1710 | } |
| 1711 | } |
| 1712 | |
| 1713 | private var sortMenu: some View { |
| 1714 | Menu { |
| 1715 | Picker("Sort drafts", selection: $draftSort) { |
| 1716 | ForEach(DraftSort.allCases, id: \.self) { option in |
| 1717 | Text(option.rawValue).tag(option) |
| 1718 | } |
| 1719 | } |
| 1720 | .pickerStyle(.inline) |
| 1721 | } label: { |
| 1722 | filterMenuLabel("Sort", icon: "arrow.up.arrow.down", isFiltered: draftSort != .lastUpdated) |
| 1723 | } |
| 1724 | .buttonStyle(.plain) |
| 1725 | .accessibilityLabel("Sort drafts") |
| 1726 | .accessibilityValue(draftSort.rawValue) |
| 1727 | .accessibilityIdentifier("review.draftSort") |
| 1728 | } |
| 1729 | |
| 1730 | private var platformMenu: some View { |
| 1731 | let title = platformFilter.map(reviewPlatformName) ?? "All platforms" |
| 1732 | return Menu { |
| 1733 | Picker("Platform", selection: $platformFilter) { |
| 1734 | Label("All platforms", systemImage: "line.3.horizontal.decrease").tag(nil as String?) |
| 1735 | ForEach(platformOptions, id: \.self) { platform in |
| 1736 | Label { |
| 1737 | Text(reviewPlatformName(platform)) |
| 1738 | } icon: { |
| 1739 | platformMenuIcon(platform) |
| 1740 | } |
| 1741 | .tag(Optional(platform)) |
| 1742 | } |
| 1743 | } |
| 1744 | .pickerStyle(.inline) |
| 1745 | } label: { |
| 1746 | filterMenuLabel(title, icon: "line.3.horizontal.decrease", isFiltered: platformFilter != nil) |
| 1747 | } |
| 1748 | .buttonStyle(.plain) |
| 1749 | .accessibilityLabel("Filter by platform") |
| 1750 | .accessibilityValue(title) |
| 1751 | .accessibilityIdentifier("review.platformFilter") |
| 1752 | } |
| 1753 | |
| 1754 | private var projectMenu: some View { |
| 1755 | let title = projectOptions.first { $0.id == projectFilter }?.name ?? "All projects" |
| 1756 | return Menu { |
| 1757 | Picker("Project", selection: $projectFilter) { |
| 1758 | Label("All projects", systemImage: "folder").tag(nil as String?) |
| 1759 | ForEach(projectOptions) { project in |
| 1760 | Label(project.name, systemImage: "folder").tag(Optional(project.id)) |
| 1761 | } |
| 1762 | } |
| 1763 | .pickerStyle(.inline) |
| 1764 | } label: { |
| 1765 | filterMenuLabel(title, icon: "folder", isFiltered: projectFilter != nil) |
| 1766 | } |
| 1767 | .buttonStyle(.plain) |
| 1768 | .accessibilityLabel("Filter by project") |
| 1769 | .accessibilityValue(title) |
| 1770 | .accessibilityIdentifier("review.projectFilter") |
| 1771 | } |
| 1772 | |
| 1773 | private func filterMenuLabel(_ title: String, icon: String, isFiltered: Bool) -> some View { |
| 1774 | let compact = !dynamicTypeSize.isAccessibilitySize |
| 1775 | return HStack(spacing: compact ? 4 : 7) { |
| 1776 | Image(systemName: icon) |
| 1777 | .foregroundStyle(palette.iconAccent) |
| 1778 | Text(title).foregroundStyle(palette.text).lineLimit(1) |
| 1779 | Image(systemName: "chevron.down") |
| 1780 | .font(.system(size: 9, weight: .semibold)) |
| 1781 | .foregroundStyle(palette.muted) |
| 1782 | } |
| 1783 | .font((compact ? Font.caption : .subheadline).weight(.medium)) |
| 1784 | .padding(.horizontal, compact ? 7 : 12) |
| 1785 | .padding(.vertical, 7) |
| 1786 | .background(isFiltered ? palette.active : palette.control, in: Capsule()) |
| 1787 | .overlay { Capsule().strokeBorder(palette.line).allowsHitTesting(false) } |
| 1788 | .frame(minHeight: 44) |
| 1789 | .contentShape(Rectangle()) |
| 1790 | } |
| 1791 | |
| 1792 | @State private var newIdeaID: String? |
| 1793 | |
| 1794 | @ToolbarContentBuilder private var ideaToolbarItem: some ToolbarContent { |
| 1795 | if #available(iOS 26, *) { |
| 1796 | ToolbarItem(placement: .topBarTrailing) { StudioNewIdeaButton { draftingIdea = true } } |
| 1797 | .sharedBackgroundVisibility(.hidden) |
| 1798 | } else { |
| 1799 | ToolbarItem(placement: .topBarTrailing) { StudioNewIdeaButton { draftingIdea = true } } |
| 1800 | } |
| 1801 | } |
| 1802 | |
| 1803 | private func showCreatedIdea() { |
| 1804 | guard let id = newIdeaID else { return } |
| 1805 | filter = "Ideas" |
| 1806 | selection = id |
| 1807 | compactColumn = .detail |
| 1808 | newIdeaID = nil |
| 1809 | } |
| 1810 | |
| 1811 | @ViewBuilder private func reviewRow(_ item: CompanionLibrary.Item, in snapshot: CompanionLibrary) -> some View { |
| 1812 | let selected = wideLayout && selection == item.id |
| 1813 | NavigationLink(value: item.id) { |
| 1814 | HStack(alignment: .top, spacing: 8) { |
| 1815 | MobilePostImage(data: item.imagePreview, label: "Post image", identifier: "review.image." + item.id, thumbnail: true) |
| 1816 | VStack(alignment: .leading, spacing: 4) { |
| 1817 | Text(item.title).font(.headline).foregroundStyle(palette.text) |
| 1818 | .lineLimit(wideLayout ? 3 : nil) |
| 1819 | reviewMetadata(item, in: snapshot) |
| 1820 | if let attachment = item.attachment, attachment == .video || item.imagePreview == nil { |
| 1821 | MobileAttachmentLabel(attachment: attachment).font(.caption) |
| 1822 | } |
| 1823 | if item.isLongForm, |
| 1824 | let edit = library.pendingChanges(for: item.id).last(where: { $0.isLongFormEdit }) { |
| 1825 | let syncStatus = library.newsletterSyncStatus(for: edit) |
| 1826 | Label(syncStatus.rawValue, systemImage: syncStatus.icon) |
| 1827 | .font(.caption).foregroundStyle(palette.muted) |
| 1828 | } else if library.isChanging(item.id) { |
| 1829 | Label("iCloud sync pending", systemImage: "checkmark").font(.caption).foregroundStyle(palette.muted) |
| 1830 | } |
| 1831 | } |
| 1832 | if selected { |
| 1833 | Spacer(minLength: 0) |
| 1834 | Image(systemName: "checkmark.circle.fill") |
| 1835 | .foregroundStyle(palette.iconAccent) |
| 1836 | .accessibilityHidden(true) |
| 1837 | } |
| 1838 | } |
| 1839 | .padding(.vertical, 4) |
| 1840 | } |
| 1841 | .listRowBackground(selected ? palette.well : palette.card) |
| 1842 | .accessibilityAddTraits(selected ? .isSelected : []) |
| 1843 | .contextMenu { |
| 1844 | if item.isLongForm { |
| 1845 | if !item.shortened && !item.body.isEmpty { |
| 1846 | Button("Copy text", systemImage: "doc.on.doc") { UIPasteboard.general.string = item.body } |
| 1847 | } |
| 1848 | } else { |
| 1849 | if item.isTrashed == true { |
| 1850 | Button("Restore", systemImage: "arrow.uturn.backward") { restore(item, in: snapshot) } |
| 1851 | .disabled(library.isChanging(item.id)) |
| 1852 | } else { |
| 1853 | Button("Edit", systemImage: "pencil") { editItem = item } |
| 1854 | } |
| 1855 | Button("Copy text", systemImage: "doc.on.doc") { UIPasteboard.general.string = item.body } |
| 1856 | .disabled(item.shortened) |
| 1857 | Button(item.isTrashed == true ? "Delete permanently…" : item.kind == .idea ? "Skip idea" : "Move to Trash", systemImage: "trash", role: .destructive) { requestRemoval(item) } |
| 1858 | .disabled(item.isTrashed == true ? !library.canDelete(item.id) : library.isChanging(item.id)) |
| 1859 | } |
| 1860 | } |
| 1861 | .swipeActions(edge: .trailing, allowsFullSwipe: false) { |
| 1862 | if !item.isLongForm { |
| 1863 | Button(item.isTrashed == true ? "Delete" : item.kind == .idea ? "Skip" : "Trash", systemImage: "trash", role: .destructive) { requestRemoval(item) } |
| 1864 | .disabled(item.isTrashed == true ? !library.canDelete(item.id) : library.isChanging(item.id)) |
| 1865 | } |
| 1866 | } |
| 1867 | .swipeActions(edge: .leading, allowsFullSwipe: false) { |
| 1868 | if !item.isLongForm { |
| 1869 | if item.isTrashed == true { |
| 1870 | Button("Restore", systemImage: "arrow.uturn.backward") { restore(item, in: snapshot) }.tint(palette.iconAccent) |
| 1871 | .disabled(library.isChanging(item.id)) |
| 1872 | } else { |
| 1873 | Button("Edit", systemImage: "pencil") { editItem = item }.tint(palette.iconAccent) |
| 1874 | } |
| 1875 | } |
| 1876 | } |
| 1877 | } |
| 1878 | |
| 1879 | private func reviewMetadata(_ item: CompanionLibrary.Item, in snapshot: CompanionLibrary) -> some View { |
| 1880 | let updatedAt = library.lastUpdated(item) |
| 1881 | return ViewThatFits(in: .horizontal) { |
| 1882 | HStack(spacing: 5) { |
| 1883 | reviewContext(item, in: snapshot) |
| 1884 | if updatedAt != nil { Text("·").accessibilityHidden(true) } |
| 1885 | MobileLastUpdated(date: updatedAt) |
| 1886 | } |
| 1887 | .fixedSize(horizontal: true, vertical: false) |
| 1888 | VStack(alignment: .leading, spacing: 3) { |
| 1889 | reviewContext(item, in: snapshot) |
| 1890 | MobileLastUpdated(date: updatedAt) |
| 1891 | } |
| 1892 | } |
| 1893 | .font(.caption) |
| 1894 | .foregroundStyle(palette.muted) |
| 1895 | } |
| 1896 | |
| 1897 | @ViewBuilder private func reviewContext(_ item: CompanionLibrary.Item, in snapshot: CompanionLibrary) -> some View { |
| 1898 | let showsPlatform = !item.reviewPlatform.isEmpty |
| 1899 | HStack(spacing: 5) { |
| 1900 | if showsPlatform { |
| 1901 | StudioPlatformLabel(name: item.reviewPlatform, title: reviewPlatformName(item.reviewPlatform)) |
| 1902 | } |
| 1903 | if filter != "Drafts" || item.isLongForm || !showsPlatform { |
| 1904 | if showsPlatform { Text("·").accessibilityHidden(true) } |
| 1905 | Text(projectName(item, in: snapshot)) |
| 1906 | } |
| 1907 | if item.isTrashed == true || (item.kind == .idea || item.isLongForm) && item.status != "draft" { |
| 1908 | Text("·").accessibilityHidden(true) |
| 1909 | Text(status(item)) |
| 1910 | } |
| 1911 | } |
| 1912 | } |
| 1913 | |
| 1914 | private func platformMenuIcon(_ platform: String) -> Image { |
| 1915 | let markPlatform = platform.hasSuffix("-article") ? String(platform.dropLast("-article".count)) : platform |
| 1916 | guard let mark = PlatformMark.bitmap(markPlatform) ?? (platform == "youtube" ? UIImage(systemName: "play.rectangle.fill") : nil) else { return Image(systemName: "link") } |
| 1917 | // Native menus lay out the image itself, independently of SwiftUI label styles. |
| 1918 | let tinted = mark.withTintColor(UIColor(palette.iconAccent), renderingMode: .alwaysOriginal) |
| 1919 | let canvas = CGSize(width: 24, height: 24) |
| 1920 | let image = UIGraphicsImageRenderer(size: canvas).image { _ in |
| 1921 | tinted.draw(in: CGRect(x: 5.5, y: 5.5, width: 13, height: 13)) |
| 1922 | } |
| 1923 | return Image(uiImage: image).renderingMode(.original) |
| 1924 | } |
| 1925 | |
| 1926 | @ViewBuilder private var reviewFilters: some View { |
| 1927 | if palette.theme == .paper { |
| 1928 | HStack(spacing: 2) { |
| 1929 | ForEach(Self.filters, id: \.self) { option in |
| 1930 | Button { filter = option } label: { |
| 1931 | Text(option) |
| 1932 | .font(.subheadline.weight(filter == option ? .semibold : .medium)) |
| 1933 | .foregroundStyle(palette.text) |
| 1934 | .frame(maxWidth: .infinity, minHeight: 40) |
| 1935 | .padding(.vertical, 2) |
| 1936 | .background(filter == option ? palette.active : .clear, in: Capsule()) |
| 1937 | .contentShape(Capsule()) |
| 1938 | } |
| 1939 | .buttonStyle(.plain) |
| 1940 | .accessibilityAddTraits(filter == option ? .isSelected : []) |
| 1941 | } |
| 1942 | } |
| 1943 | .padding(3) |
| 1944 | .background(palette.well, in: Capsule()) |
| 1945 | .overlay { Capsule().strokeBorder(palette.line).allowsHitTesting(false) } |
| 1946 | .accessibilityElement(children: .contain) |
| 1947 | .accessibilityLabel("Content") |
| 1948 | } else { |
| 1949 | Picker("Content", selection: $filter) { |
| 1950 | ForEach(Self.filters, id: \.self) { Text($0) } |
| 1951 | } |
| 1952 | .pickerStyle(.segmented) |
| 1953 | } |
| 1954 | } |
| 1955 | |
| 1956 | private func removeSelectedItem() { |
| 1957 | guard let item = deleteItem else { return } |
| 1958 | remove(item, action: .deleteItem) |
| 1959 | deleteItem = nil |
| 1960 | } |
| 1961 | |
| 1962 | private func requestRemoval(_ item: CompanionLibrary.Item) { |
| 1963 | if item.isTrashed == true { deleteItem = item } |
| 1964 | else { remove(item, action: .trashItem) } |
| 1965 | } |
| 1966 | |
| 1967 | private func remove(_ item: CompanionLibrary.Item, action: CompanionLibrary.Change.Action) { |
| 1968 | guard let snapshot = library.snapshot else { return } |
| 1969 | do { |
| 1970 | try library.saveChange(.init(action: action, itemID: item.id, revision: item.revision), workspaceID: snapshot.workspaceID) |
| 1971 | updateSelection() |
| 1972 | } catch { actionError = error.localizedDescription } |
| 1973 | } |
| 1974 | |
| 1975 | private func updateSelection() { |
| 1976 | guard !items.contains(where: { $0.id == selection }) else { return } |
| 1977 | selection = wideLayout ? items.first?.id : nil |
| 1978 | } |
| 1979 | |
| 1980 | private func restore(_ item: CompanionLibrary.Item, in snapshot: CompanionLibrary) { |
| 1981 | do { try library.saveChange(.init(action: .restoreItem, itemID: item.id, revision: item.revision), workspaceID: snapshot.workspaceID) } |
| 1982 | catch { actionError = error.localizedDescription } |
| 1983 | } |
| 1984 | |
| 1985 | private func projectName(_ item: CompanionLibrary.Item, in snapshot: CompanionLibrary) -> String { |
| 1986 | snapshot.projects.first { $0.id == item.projectID }?.name ?? "Inkspring" |
| 1987 | } |
| 1988 | |
| 1989 | private func status(_ item: CompanionLibrary.Item) -> String { |
| 1990 | if item.isTrashed == true { return item.kind == .draft ? "Trashed draft" : "Trashed idea" } |
| 1991 | return switch item.status { |
| 1992 | case "draft": item.kind == .idea ? "Open idea" : "Draft" |
| 1993 | case "queued": "Scheduled" |
| 1994 | case "due": "Needs review" |
| 1995 | case "ready": "Ready to schedule" |
| 1996 | case "picked": "Drafted" |
| 1997 | default: item.status.capitalized |
| 1998 | } |
| 1999 | } |
| 2000 | } |
| 2001 | |
| 2002 | private extension CompanionLibrary.Item { |
| 2003 | var reviewPlatform: String { |
| 2004 | let channel = platform.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() |
| 2005 | return kind == .article ? (channel == "linkedin" ? "linkedin-article" : "x-article") : channel |
| 2006 | } |
| 2007 | } |
| 2008 | |
| 2009 | private func mobileWritingKind(_ kind: String?) -> CompanionLibrary.Item.Kind { |
| 2010 | if kind == "linkedin-article" { return .article } |
| 2011 | return kind.flatMap(CompanionLibrary.Item.Kind.init(rawValue:)) ?? .script |
| 2012 | } |
| 2013 | |
| 2014 | private func mobileWritingPlatform(_ kind: String?) -> String { |
| 2015 | switch kind { |
| 2016 | case "newsletter": "substack" |
| 2017 | case "article": "x" |
| 2018 | case "linkedin-article": "linkedin" |
| 2019 | default: "youtube" |
| 2020 | } |
| 2021 | } |
| 2022 | |
| 2023 | private func reviewPlatformName(_ platform: String) -> String { |
| 2024 | switch platform { |
| 2025 | case "x": "X" |
| 2026 | case "linkedin": "LinkedIn" |
| 2027 | case "tiktok": "TikTok" |
| 2028 | case "youtube": "YouTube" |
| 2029 | case "youtube-script": "YouTube script" |
| 2030 | case "x-article": "X article" |
| 2031 | case "linkedin-article": "LinkedIn article" |
| 2032 | default: platform.capitalized |
| 2033 | } |
| 2034 | } |
| 2035 | |
| 2036 | private struct MobileXGeneration: View { |
| 2037 | @Environment(\.studioPalette) private var palette |
| 2038 | let library: MobileLibrary |
| 2039 | @State private var projectID = "" |
| 2040 | @State private var title = "" |
| 2041 | @State private var brief = "" |
| 2042 | @State private var format = "post" |
| 2043 | @State private var message: String? |
| 2044 | @State private var queued = false |
| 2045 | @State private var selection: CompanionLibrary.WritingSelection? |
| 2046 | |
| 2047 | var body: some View { |
| 2048 | Form { |
| 2049 | Section { |
| 2050 | if let projects = library.snapshot?.projects { |
| 2051 | Picker("Project", selection: $projectID) { |
| 2052 | ForEach(projects) { Text($0.name).tag($0.id) } |
| 2053 | } |
| 2054 | } |
| 2055 | TextField("Draft title", text: $title, axis: .vertical) |
| 2056 | Picker("X post type", selection: $format) { |
| 2057 | ForEach(XPostStyle.allCases) { Text($0.title).tag($0.rawValue) } |
| 2058 | } |
| 2059 | .accessibilityIdentifier("x.generationType") |
| 2060 | TextField("What should the post be about?", text: $brief, axis: .vertical).lineLimit(4...10) |
| 2061 | if let providers = library.snapshot?.writingProviders, !providers.isEmpty { |
| 2062 | MobileWritingPicker(providers: providers, preferredProvider: library.snapshot?.writingAgent, selection: $selection) |
| 2063 | } |
| 2064 | Button("Generate on my Mac", systemImage: "sparkles") { |
| 2065 | guard let snapshot = library.snapshot else { return } |
| 2066 | do { |
| 2067 | var change = CompanionLibrary.Change(action: .addIdea, itemID: projectID, title: title, |
| 2068 | text: brief, xFormat: format, generatesXDraft: true) |
| 2069 | change.writingSelection = MobileWritingPicker.resolved(selection, providers: snapshot.writingProviders, |
| 2070 | preferred: snapshot.writingAgent) |
| 2071 | try library.saveChange(change, workspaceID: snapshot.workspaceID) |
| 2072 | queued = true |
| 2073 | message = "Queued for your Mac. The generated draft will appear in Review." |
| 2074 | } catch { message = error.localizedDescription } |
| 2075 | } |
| 2076 | .disabled(queued || !library.canUseAgentFeatures || library.snapshot?.supportsXThreads != true || projectID.isEmpty || |
| 2077 | !MobileWritingPicker.canSend(MobileWritingPicker.resolved(selection, providers: library.snapshot?.writingProviders, |
| 2078 | preferred: library.snapshot?.writingAgent), providers: library.snapshot?.writingProviders) || |
| 2079 | title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || |
| 2080 | title.utf16.count > 200 || brief.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || |
| 2081 | brief.utf16.count > 10_000) |
| 2082 | .accessibilityIdentifier("x.generate") |
| 2083 | Text("Your Mac uses your writing connection. Keep Inkspring open there.").font(.footnote) |
| 2084 | if let message { Text(message).font(.callout) } |
| 2085 | } |
| 2086 | .listRowBackground(palette.card) |
| 2087 | .disabled(queued) |
| 2088 | } |
| 2089 | .scrollContentBackground(.hidden).background(palette.canvas) |
| 2090 | .navigationTitle("Draft for X").navigationBarTitleDisplayMode(.inline) |
| 2091 | .onAppear { |
| 2092 | projectID = library.snapshot?.projects.first?.id ?? "" |
| 2093 | } |
| 2094 | } |
| 2095 | } |
| 2096 | |
| 2097 | private struct MobilePrimaryActionStyle: ButtonStyle { |
| 2098 | @Environment(\.studioPalette) private var palette |
| 2099 | @Environment(\.isEnabled) private var isEnabled |
| 2100 | var fillsWidth = true |
| 2101 | |
| 2102 | func makeBody(configuration: Configuration) -> some View { |
| 2103 | let shape = RoundedRectangle(cornerRadius: StudioRadius.card) |
| 2104 | let foreground = isEnabled ? palette.accentText : palette.disabledText |
| 2105 | return configuration.label |
| 2106 | .labelStyle(.titleAndIcon) |
| 2107 | .font(.body.weight(.semibold)) |
| 2108 | .multilineTextAlignment(.center) |
| 2109 | .foregroundStyle(foreground) |
| 2110 | .padding(.horizontal, 14) |
| 2111 | .padding(.vertical, 10) |
| 2112 | .frame(maxWidth: fillsWidth ? .infinity : nil, minHeight: 48) |
| 2113 | .background(isEnabled ? palette.primaryAction : palette.well, in: shape) |
| 2114 | .overlay { |
| 2115 | if isEnabled && configuration.isPressed { |
| 2116 | shape.strokeBorder(foreground.opacity(0.45), lineWidth: 2) |
| 2117 | .allowsHitTesting(false) |
| 2118 | } else if !isEnabled { |
| 2119 | shape.strokeBorder(palette.line).allowsHitTesting(false) |
| 2120 | } |
| 2121 | } |
| 2122 | .contentShape(shape) |
| 2123 | } |
| 2124 | } |
| 2125 | |
| 2126 | struct MobileWritingPicker: View { |
| 2127 | @Environment(\.studioPalette) private var palette |
| 2128 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 2129 | let providers: [CompanionLibrary.WritingProvider] |
| 2130 | let preferredProvider: String? |
| 2131 | @Binding var selection: CompanionLibrary.WritingSelection? |
| 2132 | @State private var showsModels = false |
| 2133 | |
| 2134 | static func resolved(_ selection: CompanionLibrary.WritingSelection?, providers: [CompanionLibrary.WritingProvider]?, |
| 2135 | preferred: String?) -> CompanionLibrary.WritingSelection? { |
| 2136 | guard let providers, |
| 2137 | let provider = providers.first(where: { $0.id == selection?.provider }) |
| 2138 | ?? providers.first(where: { $0.id == preferred }) ?? providers.first else { return nil } |
| 2139 | let model = provider.id == selection?.provider ? selection?.model : nil |
| 2140 | return .init(provider: provider.id, model: model) |
| 2141 | } |
| 2142 | |
| 2143 | static func canSend(_ selection: CompanionLibrary.WritingSelection?, providers: [CompanionLibrary.WritingProvider]?) -> Bool { |
| 2144 | guard let providers else { return true } |
| 2145 | guard let selection, let provider = providers.first(where: { $0.id == selection.provider }), provider.isAvailable else { |
| 2146 | return false |
| 2147 | } |
| 2148 | return selection.model.map { id in provider.models.contains { $0.id == id } } ?? true |
| 2149 | } |
| 2150 | |
| 2151 | var body: some View { |
| 2152 | if let current = Self.resolved(selection, providers: providers, preferred: preferredProvider), |
| 2153 | let provider = providers.first(where: { $0.id == current.provider }) { |
| 2154 | let defaultName = provider.models.first { $0.id == provider.defaultModel }?.name |
| 2155 | let defaultLabel = defaultName.map { "Mac default (\($0))" } ?? "Mac default" |
| 2156 | let modelName = current.model.map { id in provider.models.first { $0.id == id }?.name ?? "Choose a model" } ?? defaultLabel |
| 2157 | let providerLayout = dynamicTypeSize.isAccessibilitySize |
| 2158 | ? AnyLayout(VStackLayout(spacing: 4)) : AnyLayout(HStackLayout(spacing: 4)) |
| 2159 | VStack(alignment: .leading, spacing: 10) { |
| 2160 | Text("Provider").font(.subheadline.weight(.semibold)) |
| 2161 | providerLayout { |
| 2162 | ForEach(providers) { option in |
| 2163 | Button { |
| 2164 | guard option.id != current.provider else { return } |
| 2165 | selection = option.id == preferredProvider ? nil : .init(provider: option.id, model: nil) |
| 2166 | showsModels = false |
| 2167 | } label: { |
| 2168 | StudioPlatformLabel(name: Self.icon(for: option.id), title: option.name) |
| 2169 | .font(.subheadline.weight(.semibold)) |
| 2170 | .frame(maxWidth: .infinity, minHeight: 44) |
| 2171 | .background(current.provider == option.id ? palette.active : .clear, in: Capsule()) |
| 2172 | .contentShape(Capsule()) |
| 2173 | } |
| 2174 | .buttonStyle(.plain) |
| 2175 | .accessibilityAddTraits(current.provider == option.id ? .isSelected : []) |
| 2176 | .accessibilityIdentifier("writing.provider.\(option.id)") |
| 2177 | } |
| 2178 | } |
| 2179 | .padding(3) |
| 2180 | .background(palette.well, in: RoundedRectangle(cornerRadius: 24)) |
| 2181 | .overlay { RoundedRectangle(cornerRadius: 24).strokeBorder(palette.line).allowsHitTesting(false) } |
| 2182 | |
| 2183 | Button { |
| 2184 | showsModels.toggle() |
| 2185 | } label: { |
| 2186 | HStack(spacing: 12) { |
| 2187 | VStack(alignment: .leading, spacing: 3) { |
| 2188 | Text("Model").font(.caption.weight(.medium)).foregroundStyle(palette.muted) |
| 2189 | Text(modelName).font(.subheadline.weight(.semibold)) |
| 2190 | } |
| 2191 | Spacer() |
| 2192 | Image(systemName: showsModels ? "chevron.up" : "chevron.down") |
| 2193 | .font(.caption.weight(.semibold)).foregroundStyle(palette.iconAccent) |
| 2194 | .accessibilityHidden(true) |
| 2195 | } |
| 2196 | .padding(.horizontal, 14).padding(.vertical, 10) |
| 2197 | .frame(minHeight: 48) |
| 2198 | .studioSurface(fill: palette.well) |
| 2199 | .contentShape(Rectangle()) |
| 2200 | .accessibilityElement(children: .combine) |
| 2201 | } |
| 2202 | .buttonStyle(.plain) |
| 2203 | .accessibilityIdentifier("writing.model.open") |
| 2204 | |
| 2205 | if !provider.isAvailable { |
| 2206 | Text("Connect \(provider.name) on your Mac to use it here.") |
| 2207 | .font(.footnote).foregroundStyle(palette.muted) |
| 2208 | } else if selection != nil { |
| 2209 | Button("Use Mac defaults") { |
| 2210 | selection = nil |
| 2211 | showsModels = false |
| 2212 | } |
| 2213 | .buttonStyle(.plain) |
| 2214 | .font(.footnote.weight(.semibold)) |
| 2215 | .foregroundStyle(palette.iconAccent) |
| 2216 | .accessibilityIdentifier("writing.reset") |
| 2217 | } |
| 2218 | |
| 2219 | if showsModels { |
| 2220 | VStack(spacing: 0) { |
| 2221 | modelRow(defaultLabel, id: nil, current: current) |
| 2222 | ForEach(provider.models) { model in |
| 2223 | Divider().padding(.horizontal, 14) |
| 2224 | modelRow(model.name, id: model.id, current: current) |
| 2225 | } |
| 2226 | } |
| 2227 | .studioSurface() |
| 2228 | } |
| 2229 | } |
| 2230 | .foregroundStyle(palette.text) |
| 2231 | } |
| 2232 | } |
| 2233 | |
| 2234 | private static func icon(for provider: String) -> String { |
| 2235 | switch provider { |
| 2236 | case "claude", "anthropic": "claude-mark" |
| 2237 | case "codex", "openai": "openai-mark" |
| 2238 | case "antigravity": "gemini" |
| 2239 | default: provider |
| 2240 | } |
| 2241 | } |
| 2242 | |
| 2243 | private func modelRow(_ name: String, id: String?, current: CompanionLibrary.WritingSelection) -> some View { |
| 2244 | Button { |
| 2245 | selection = .init(provider: current.provider, model: id) |
| 2246 | showsModels = false |
| 2247 | } label: { |
| 2248 | HStack { |
| 2249 | Text(name).font(.subheadline) |
| 2250 | Spacer() |
| 2251 | if current.model == id { |
| 2252 | Image(systemName: "checkmark").font(.subheadline.weight(.semibold)) |
| 2253 | .foregroundStyle(palette.iconAccent).accessibilityHidden(true) |
| 2254 | } |
| 2255 | } |
| 2256 | .padding(.horizontal, 14) |
| 2257 | .frame(minHeight: 44) |
| 2258 | .contentShape(Rectangle()) |
| 2259 | } |
| 2260 | .buttonStyle(.plain) |
| 2261 | .accessibilityAddTraits(current.model == id ? .isSelected : []) |
| 2262 | .accessibilityIdentifier("writing.model.\(id ?? "default")") |
| 2263 | } |
| 2264 | } |
| 2265 | |
| 2266 | private struct MobileIdeaDraftPicker: View { |
| 2267 | @Environment(\.studioPalette) private var palette |
| 2268 | let item: CompanionLibrary.Item |
| 2269 | let library: MobileLibrary |
| 2270 | let workspaceID: UUID |
| 2271 | let onQueued: ([String], String) -> Void |
| 2272 | @State private var chosen: Set<String> = [] |
| 2273 | @State private var message: String? |
| 2274 | @State private var selection: CompanionLibrary.WritingSelection? |
| 2275 | |
| 2276 | private var compatibleMac: Bool { library.canUseAgentFeatures && library.snapshot?.supportsClaudeIdeaDrafts == true } |
| 2277 | private var hasIdeaImage: Bool { item.attachment == .image && library.snapshot?.supportsIdeaImages == true } |
| 2278 | private var platforms: [String] { CompanionLibrary.draftPlatforms(hasIdeaImage: hasIdeaImage) } |
| 2279 | private var providers: [CompanionLibrary.WritingProvider]? { library.snapshot?.writingProviders } |
| 2280 | private var preferredProvider: String? { library.snapshot?.writingAgent } |
| 2281 | private var writer: CompanionLibrary.WritingSelection? { |
| 2282 | MobileWritingPicker.resolved(selection, providers: providers, preferred: preferredProvider) |
| 2283 | } |
| 2284 | private var writerName: String { |
| 2285 | providers?.first(where: { $0.id == writer?.provider })?.name ?? "Claude" |
| 2286 | } |
| 2287 | |
| 2288 | var body: some View { |
| 2289 | Form { |
| 2290 | if let providers, !providers.isEmpty { |
| 2291 | Section("Writing on your Mac") { |
| 2292 | MobileWritingPicker(providers: providers, preferredProvider: preferredProvider, selection: $selection) |
| 2293 | } |
| 2294 | .listRowBackground(palette.card) |
| 2295 | } |
| 2296 | Section { |
| 2297 | ForEach(platforms, id: \.self) { platform in |
| 2298 | if item.draftedIdeaPlatforms?.contains(platform) == true { |
| 2299 | Label("\(ideaDraftLabel(platform)) draft exists", systemImage: "checkmark.circle.fill") |
| 2300 | .foregroundStyle(palette.muted) |
| 2301 | } else { |
| 2302 | Button { |
| 2303 | if chosen.contains(platform) { chosen.remove(platform) } |
| 2304 | else { chosen.insert(platform) } |
| 2305 | } label: { |
| 2306 | HStack { |
| 2307 | Label(ideaDraftLabel(platform), systemImage: platform.hasSuffix("-article") || platform == "substack" ? "doc.richtext" : "text.bubble") |
| 2308 | Spacer() |
| 2309 | Image(systemName: chosen.contains(platform) ? "checkmark.circle.fill" : "circle") |
| 2310 | .foregroundStyle(chosen.contains(platform) ? palette.iconAccent : palette.muted) |
| 2311 | .accessibilityHidden(true) |
| 2312 | } |
| 2313 | .frame(minHeight: 35) |
| 2314 | .contentShape(Rectangle()) |
| 2315 | } |
| 2316 | .buttonStyle(.plain) |
| 2317 | .accessibilityAddTraits(chosen.contains(platform) ? .isSelected : []) |
| 2318 | .accessibilityIdentifier("idea.draft.platform.\(platform)") |
| 2319 | } |
| 2320 | } |
| 2321 | } header: { |
| 2322 | Text("Drafts to create") |
| 2323 | } footer: { |
| 2324 | if hasIdeaImage { Text("The idea image is sized for each photo post you draft.") } |
| 2325 | } |
| 2326 | .listRowBackground(palette.card) |
| 2327 | } |
| 2328 | .scrollContentBackground(.hidden) |
| 2329 | .background(palette.canvas) |
| 2330 | .safeAreaInset(edge: .bottom, spacing: 0) { |
| 2331 | VStack(spacing: 8) { |
| 2332 | Button { |
| 2333 | queueDrafts() |
| 2334 | } label: { |
| 2335 | Label("Send to \(writerName)", systemImage: "paperplane") |
| 2336 | } |
| 2337 | .buttonStyle(MobilePrimaryActionStyle()) |
| 2338 | .disabled(chosen.isEmpty || !compatibleMac || !MobileWritingPicker.canSend(writer, providers: providers)) |
| 2339 | .accessibilityIdentifier("idea.draft.send") |
| 2340 | Text(message ?? (providers?.isEmpty == true |
| 2341 | ? "Enable agent access and sign in to Claude or Codex on your Mac." |
| 2342 | : compatibleMac |
| 2343 | ? (chosen.contains("x") ? "Your Mac writes a follow-up for links in the idea. Find the draft in Review." |
| 2344 | : "Your Mac creates one draft per selection. Find them in Review.") |
| 2345 | : "Update and open Inkspring on your Mac, then refresh here to send post ideas to Claude.")) |
| 2346 | .font(.footnote) |
| 2347 | .foregroundStyle(message == nil ? palette.muted : palette.danger) |
| 2348 | .multilineTextAlignment(.center) |
| 2349 | } |
| 2350 | .padding(.horizontal, 20) |
| 2351 | .padding(.vertical, 12) |
| 2352 | .background(palette.canvas) |
| 2353 | } |
| 2354 | .navigationTitle("Draft from post idea").navigationBarTitleDisplayMode(.inline) |
| 2355 | } |
| 2356 | |
| 2357 | private func queueDrafts() { |
| 2358 | let platforms = platforms.filter(chosen.contains) |
| 2359 | guard !platforms.isEmpty else { return } |
| 2360 | var change = CompanionLibrary.Change(action: .note, itemID: item.id, revision: item.revision, |
| 2361 | xFormat: chosen.contains("x") ? XPostStyle.post.rawValue : nil) |
| 2362 | change.ideaDraftPlatforms = platforms |
| 2363 | change.writingSelection = writer |
| 2364 | do { |
| 2365 | try library.saveChange(change, workspaceID: workspaceID) |
| 2366 | chosen.removeAll() |
| 2367 | onQueued(platforms, writerName) |
| 2368 | } catch { message = error.localizedDescription } |
| 2369 | } |
| 2370 | |
| 2371 | private func ideaDraftLabel(_ platform: String) -> String { |
| 2372 | switch platform { |
| 2373 | case "x": "X post" |
| 2374 | case "linkedin": "LinkedIn post" |
| 2375 | case "reddit": "Reddit post" |
| 2376 | case "instagram": "Instagram photo" |
| 2377 | case "tiktok": "TikTok photo" |
| 2378 | case "substack": "Substack article or newsletter" |
| 2379 | case "youtube": "YouTube script" |
| 2380 | default: reviewPlatformName(platform) |
| 2381 | } |
| 2382 | } |
| 2383 | } |
| 2384 | |
| 2385 | private struct MobileQuickXComposer: View { |
| 2386 | let library: MobileLibrary |
| 2387 | let preferredProject: String? |
| 2388 | @Environment(\.dismiss) private var dismiss |
| 2389 | @Environment(\.studioPalette) private var palette |
| 2390 | @State private var text = "" |
| 2391 | @State private var projectID: String? |
| 2392 | @State private var confirming = false |
| 2393 | @State private var requestID: UUID? |
| 2394 | @State private var error: String? |
| 2395 | @State private var polishing = false |
| 2396 | @State private var suggestedText: String? |
| 2397 | @FocusState private var editingPost: Bool |
| 2398 | |
| 2399 | private var projects: [CompanionLibrary.Project] { library.snapshot?.projects ?? [] } |
| 2400 | private var project: String? { projectID ?? preferredProject ?? projects.first?.id } |
| 2401 | private var account: String? { library.snapshot?.xArticleAccountKey } |
| 2402 | private var accountName: String { library.snapshot?.xArticleAccountName ?? "your connected account" } |
| 2403 | private var post: String { text.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 2404 | private var weight: Int { XThreadText.weight(post) } |
| 2405 | private var canPost: Bool { |
| 2406 | library.snapshot?.supportsQuickXPost == true && account != nil && project != nil && requestID == nil |
| 2407 | && XThreadText.validSinglePost(post) |
| 2408 | } |
| 2409 | |
| 2410 | var body: some View { |
| 2411 | ScrollView { |
| 2412 | VStack(alignment: .leading, spacing: 16) { |
| 2413 | if let requestID { |
| 2414 | publicationStatus(requestID) |
| 2415 | .frame(maxWidth: .infinity, alignment: .leading) |
| 2416 | .padding(16) |
| 2417 | .studioSurface() |
| 2418 | } else { |
| 2419 | composer |
| 2420 | } |
| 2421 | } |
| 2422 | .padding(20) |
| 2423 | .frame(maxWidth: 620) |
| 2424 | .frame(maxWidth: .infinity) |
| 2425 | } |
| 2426 | .scrollDismissesKeyboard(.interactively) |
| 2427 | .mobileCanvas() |
| 2428 | .navigationTitle("Quick X post") |
| 2429 | .navigationBarTitleDisplayMode(.inline) |
| 2430 | .toolbar { ToolbarItem(placement: .cancellationAction) { Button(requestID == nil ? "Cancel" : "Done") { dismiss() } } } |
| 2431 | .alert("Publish this post to \(accountName)?", isPresented: $confirming) { |
| 2432 | Button("Cancel", role: .cancel) {} |
| 2433 | Button("Publish to X", action: publish) |
| 2434 | } message: { |
| 2435 | Text(post) |
| 2436 | } |
| 2437 | } |
| 2438 | |
| 2439 | private var composer: some View { |
| 2440 | VStack(alignment: .leading, spacing: 12) { |
| 2441 | if projects.count > 1 { |
| 2442 | Picker("Project", selection: Binding(get: { project ?? "" }, set: { projectID = $0 })) { |
| 2443 | ForEach(projects) { Text($0.name).tag($0.id) } |
| 2444 | } |
| 2445 | } |
| 2446 | TextField("Your post", text: $text, |
| 2447 | prompt: Text("Write the one thing you want to say."), axis: .vertical) |
| 2448 | .textFieldStyle(.plain) |
| 2449 | .lineLimit(4...10) |
| 2450 | .focused($editingPost) |
| 2451 | .accessibilityIdentifier("quickX.text") |
| 2452 | .padding(14) |
| 2453 | .studioSurface() |
| 2454 | Text("\(weight) / 280") |
| 2455 | .font(.caption) |
| 2456 | .foregroundStyle(weight > 280 ? palette.danger : palette.muted) |
| 2457 | .frame(maxWidth: .infinity, alignment: .trailing) |
| 2458 | StudioProofreadAction(document: .init(title: "", body: text), |
| 2459 | unavailable: proofreadUnavailable, begin: { editingPost = false }, reviewInSheet: true, |
| 2460 | check: proofread) { text = $0.body } |
| 2461 | if MobileProofreading.availabilityMessage == nil { |
| 2462 | Button("Polish with Apple Intelligence", systemImage: "sparkles") { |
| 2463 | editingPost = false |
| 2464 | Task { await polish() } |
| 2465 | } |
| 2466 | .buttonStyle(.bordered) |
| 2467 | .disabled(polishing || post.isEmpty || weight > 1_000) |
| 2468 | } |
| 2469 | if polishing { ProgressView("Polishing…") } |
| 2470 | if let suggestedText { |
| 2471 | Text(suggestedText).textSelection(.enabled) |
| 2472 | HStack { |
| 2473 | Button("Use this version") { text = suggestedText; self.suggestedText = nil } |
| 2474 | Button("Dismiss") { self.suggestedText = nil } |
| 2475 | } |
| 2476 | .buttonStyle(.bordered) |
| 2477 | } |
| 2478 | Button("Post to X", systemImage: "paperplane") { |
| 2479 | editingPost = false |
| 2480 | confirming = true |
| 2481 | } |
| 2482 | .buttonStyle(MobilePrimaryActionStyle()) |
| 2483 | .disabled(!canPost) |
| 2484 | .accessibilityIdentifier("quickX.review") |
| 2485 | Text("Your Mac publishes this as a single post to \(accountName).") |
| 2486 | .font(.footnote).foregroundStyle(palette.muted) |
| 2487 | if library.snapshot?.supportsQuickXPost != true { |
| 2488 | Text("Update and open Inkspring on your Mac to use Quick X.") |
| 2489 | } else if account == nil { |
| 2490 | Text("Connect your X account in Inkspring on your Mac.") |
| 2491 | } |
| 2492 | if let error { Label(error, systemImage: "exclamationmark.circle") } |
| 2493 | } |
| 2494 | } |
| 2495 | |
| 2496 | @ViewBuilder private func publicationStatus(_ id: UUID) -> some View { |
| 2497 | if let result = library.snapshot?.results.first(where: { $0.id == id }) { |
| 2498 | if let error = result.error { |
| 2499 | Label(error, systemImage: "exclamationmark.circle") |
| 2500 | } else if let address = result.publicationURL, let url = CompanionPublication.postURL(address) { |
| 2501 | Link("View published post", destination: url) |
| 2502 | .accessibilityIdentifier("quickX.published") |
| 2503 | } else { |
| 2504 | Label("Published on X", systemImage: "checkmark.circle") |
| 2505 | } |
| 2506 | } else if let error = library.pendingQuickXPosts.first(where: { $0.id == id })?.error { |
| 2507 | Label(error, systemImage: "exclamationmark.circle") |
| 2508 | } else { |
| 2509 | Label("Waiting for your Mac to publish.", systemImage: "clock") |
| 2510 | } |
| 2511 | } |
| 2512 | |
| 2513 | private func publish() { |
| 2514 | guard canPost, let account, let project else { return } |
| 2515 | do { requestID = try library.queueQuickXPost(text: post, projectID: project, accountKey: account) } |
| 2516 | catch { self.error = error.localizedDescription } |
| 2517 | } |
| 2518 | |
| 2519 | private var proofreadUnavailable: String? { |
| 2520 | #if DEBUG |
| 2521 | if ProcessInfo.processInfo.arguments.contains("--quick-x-fixture") { return nil } |
| 2522 | #endif |
| 2523 | return MobileProofreading.availabilityMessage |
| 2524 | } |
| 2525 | |
| 2526 | @MainActor private func proofread(_ document: ProofreadDocument) async throws -> ProofreadReview { |
| 2527 | #if DEBUG |
| 2528 | if ProcessInfo.processInfo.arguments.contains("--quick-x-fixture") { |
| 2529 | return try await ProofreadReview.check(document, chunkSize: 1_350) { _ in |
| 2530 | [.init(original: "teh", replacement: "the", reason: "Fix a spelling error")] |
| 2531 | } |
| 2532 | } |
| 2533 | #endif |
| 2534 | return try await MobileProofreading.check(document) |
| 2535 | } |
| 2536 | |
| 2537 | private func polish() async { |
| 2538 | guard #available(iOS 26, *), MobileProofreading.availabilityMessage == nil, !polishing else { return } |
| 2539 | let original = text |
| 2540 | polishing = true |
| 2541 | error = nil |
| 2542 | defer { polishing = false } |
| 2543 | do { |
| 2544 | let session = LanguageModelSession(instructions: """ |
| 2545 | Tighten the author's text into one short post for X, keeping the voice, meaning, and claims. |
| 2546 | Use the author's language. Do not add hashtags, links, or facts. Return only the post text, within 280 characters. |
| 2547 | """) |
| 2548 | let response = try await session.respond(to: original) |
| 2549 | let candidate = XThreadText.singlePost(response.content) |
| 2550 | guard original == text else { return } |
| 2551 | guard XThreadText.validSinglePost(candidate) else { |
| 2552 | error = "Apple Intelligence didn’t suggest a version that fits in one X post." |
| 2553 | return |
| 2554 | } |
| 2555 | suggestedText = candidate |
| 2556 | } catch { self.error = error.localizedDescription } |
| 2557 | } |
| 2558 | } |
| 2559 | |
| 2560 | private struct MobileMediaDraftForm: View { |
| 2561 | @Environment(\.studioPalette) private var palette |
| 2562 | @Environment(\.dismiss) private var dismiss |
| 2563 | let platform: String |
| 2564 | let library: MobileLibrary |
| 2565 | let initialProject: String |
| 2566 | let ideaID: String? |
| 2567 | @State private var projectID = "" |
| 2568 | @State private var caption = "" |
| 2569 | @State private var importing = false |
| 2570 | @State private var selected: URL? |
| 2571 | @State private var message: String? |
| 2572 | @State private var queued = false |
| 2573 | |
| 2574 | var body: some View { |
| 2575 | Form { |
| 2576 | Section { |
| 2577 | if ideaID == nil { |
| 2578 | Picker("Project", selection: $projectID) { |
| 2579 | ForEach(library.snapshot?.projects ?? []) { Text($0.name).tag($0.id) } |
| 2580 | } |
| 2581 | } |
| 2582 | Button(selected?.lastPathComponent ?? (platform == "tiktok" ? "Choose a video" : "Choose a photo or video"), |
| 2583 | systemImage: platform == "tiktok" ? "video" : "photo") { importing = true } |
| 2584 | TextField("Caption (optional)", text: $caption, axis: .vertical).lineLimit(2...4) |
| 2585 | } footer: { |
| 2586 | Text("MP4 or MOV video up to 30 MB. Instagram also accepts PNG and JPEG.") |
| 2587 | } |
| 2588 | .listRowBackground(palette.card) |
| 2589 | .disabled(queued) |
| 2590 | |
| 2591 | Section { |
| 2592 | Button("Save draft on Mac", systemImage: "square.and.pencil") { |
| 2593 | guard let selected else { return } |
| 2594 | do { |
| 2595 | try library.queueMediaDraft(file: selected, platform: platform, caption: caption, |
| 2596 | projectID: projectID, ideaID: ideaID) |
| 2597 | queued = true |
| 2598 | message = "Queued for your Mac. The draft will appear in Review." |
| 2599 | } catch { message = error.localizedDescription } |
| 2600 | } |
| 2601 | .disabled(selected == nil || projectID.isEmpty || queued || caption.utf16.count > 2_200) |
| 2602 | if let message { Text(message).font(.callout) } |
| 2603 | } |
| 2604 | .listRowBackground(palette.card) |
| 2605 | } |
| 2606 | .scrollContentBackground(.hidden) |
| 2607 | .background(palette.canvas) |
| 2608 | .navigationTitle(platform == "tiktok" ? "New TikTok video" : "New Instagram post") |
| 2609 | .navigationBarTitleDisplayMode(.inline) |
| 2610 | .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } } |
| 2611 | .onAppear { if projectID.isEmpty { projectID = initialProject } } |
| 2612 | .fileImporter(isPresented: $importing, allowedContentTypes: platform == "tiktok" ? [.mpeg4Movie, .quickTimeMovie] : [.mpeg4Movie, .quickTimeMovie, .png, .jpeg]) { result in |
| 2613 | do { selected = try result.get(); message = nil } |
| 2614 | catch { message = error.localizedDescription } |
| 2615 | } |
| 2616 | } |
| 2617 | } |
| 2618 | |
| 2619 | private struct MobileItemEditor: View { |
| 2620 | let item: CompanionLibrary.Item |
| 2621 | let library: MobileLibrary |
| 2622 | let workspaceID: UUID |
| 2623 | var bodyFirst = false |
| 2624 | var close: (() -> Void)? = nil |
| 2625 | @Environment(\.dismiss) private var dismiss |
| 2626 | @Environment(\.scenePhase) private var scenePhase |
| 2627 | @Environment(\.studioPalette) private var palette |
| 2628 | @State private var showsWritingTools = false |
| 2629 | @State private var title = "" |
| 2630 | @State private var text = "" |
| 2631 | @State private var format = "post" |
| 2632 | @State private var baseTitle = "" |
| 2633 | @State private var baseText = "" |
| 2634 | @State private var baseFormat = "post" |
| 2635 | @State private var initialized = false |
| 2636 | @State private var message: String? |
| 2637 | @State private var findRequest = 0 |
| 2638 | |
| 2639 | private var unavailable: Bool { |
| 2640 | item.isTrashed == true || item.shortened || ["posting", "posted", "uncertain"].contains(item.status) |
| 2641 | } |
| 2642 | private var dirty: Bool { title != baseTitle || text != baseText || format != baseFormat } |
| 2643 | private var recoveryKey: String { library.newsletterRecoveryKey(for: item.id, workspaceID: workspaceID) ?? "" } |
| 2644 | private var isX: Bool { |
| 2645 | item.platform == "x" && XPostStyle(rawValue: item.format ?? "post") != nil && |
| 2646 | item.requiresMacScheduling != true && library.snapshot?.supportsXThreads == true |
| 2647 | } |
| 2648 | |
| 2649 | var body: some View { |
| 2650 | VStack(spacing: 8) { |
| 2651 | HStack(alignment: .top, spacing: 10) { |
| 2652 | MobilePostImage(data: item.imagePreview, label: "Post image", identifier: "draft.image.editor", thumbnail: true) |
| 2653 | TextField("Title", text: $title, axis: .vertical).font(.headline).lineLimit(1...2) |
| 2654 | .accessibilityIdentifier("mobile.edit.title") |
| 2655 | } |
| 2656 | .padding(.horizontal, 12) |
| 2657 | if isX { |
| 2658 | StudioXPostEditor(text: $text, format: $format, articles: library.snapshot?.supportsXReplyArticles == true ? (library.snapshot?.articles ?? []).compactMap { article in |
| 2659 | guard article.platform != "linkedin", article.projectID == item.projectID, let ref = article.referenceID else { return nil } |
| 2660 | return XArticleChoice(id: ref, title: article.title) |
| 2661 | } : []).frame(maxWidth: .infinity, maxHeight: .infinity) |
| 2662 | } else { |
| 2663 | MobileWritingTextView(text: $text, identifier: "mobile.edit.body", findRequest: findRequest, onFocusLost: { _ = save() }) |
| 2664 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 2665 | } |
| 2666 | if let message { Text(message).font(.footnote).foregroundStyle(palette.danger).padding(.horizontal, 12) } |
| 2667 | } |
| 2668 | .padding(.vertical, 8).background(palette.canvas) |
| 2669 | .toolbar(.hidden, for: .tabBar) |
| 2670 | .navigationTitle(item.kind == .draft ? "Edit draft" : "Edit idea") |
| 2671 | .navigationBarTitleDisplayMode(.inline) |
| 2672 | .toolbar { |
| 2673 | ToolbarItemGroup(placement: .topBarTrailing) { |
| 2674 | if !isX { Button("Find", systemImage: "magnifyingglass") { findRequest += 1 }.accessibilityIdentifier("editor.find") } |
| 2675 | if library.canUseAgentFeatures { |
| 2676 | MobileWritingTools(title: $title, text: $text, presented: $showsWritingTools, |
| 2677 | agent: library.snapshot?.writingAgent ?? "agent", providers: library.snapshot?.writingProviders, |
| 2678 | requests: library.revisionRequests(for: item), |
| 2679 | reply: item.writingReply, error: item.writingError) { prompt, selection in |
| 2680 | guard save() else { throw CompanionLibraryError.invalid } |
| 2681 | var change = CompanionLibrary.Change(action: .note, itemID: item.id, revision: item.revision, |
| 2682 | text: prompt, requestsWritingHelp: true) |
| 2683 | change.writingSelection = selection |
| 2684 | try library.saveChange(change, workspaceID: workspaceID) |
| 2685 | } |
| 2686 | } |
| 2687 | Button("Done") { if save() { if let close { close() } else { dismiss() } } } |
| 2688 | } |
| 2689 | } |
| 2690 | .task { |
| 2691 | guard !initialized else { return } |
| 2692 | let pending = library.pendingChanges(for: item.id).last { [.editDraft, .editIdea].contains($0.action) && $0.contentOperation == nil } |
| 2693 | baseTitle = pending?.title ?? item.title |
| 2694 | baseText = pending?.text ?? item.body |
| 2695 | baseFormat = pending?.xFormat ?? item.format ?? "post" |
| 2696 | let recovery = library.recoverNewsletterEdit(key: recoveryKey) |
| 2697 | title = recovery?.title ?? baseTitle |
| 2698 | text = recovery?.markdown ?? baseText |
| 2699 | format = baseFormat |
| 2700 | initialized = true |
| 2701 | } |
| 2702 | .onChange(of: title + "\0" + text + "\0" + format) { |
| 2703 | guard initialized, dirty else { return } |
| 2704 | library.storeNewsletterRecovery(.init(revision: item.revision, base: baseText, markdown: text, title: title), key: recoveryKey) |
| 2705 | } |
| 2706 | .task(id: title + "\0" + text + "\0" + format) { |
| 2707 | guard initialized, dirty else { return } |
| 2708 | do { try await Task.sleep(for: .milliseconds(750)) } catch { return } |
| 2709 | _ = save() |
| 2710 | } |
| 2711 | .onChange(of: scenePhase) { _, phase in if phase != .active { _ = save() } } |
| 2712 | .onDisappear { _ = save() } |
| 2713 | } |
| 2714 | |
| 2715 | @discardableResult private func save() -> Bool { |
| 2716 | guard initialized, dirty else { return true } |
| 2717 | guard !unavailable else { message = "This item is not currently editable. Your text is saved on this device."; return false } |
| 2718 | do { |
| 2719 | let latest = library.snapshot?.items.first { $0.id == item.id } ?? item |
| 2720 | try library.saveChange(.init(action: item.kind == .draft ? .editDraft : .editIdea, itemID: item.id, |
| 2721 | revision: latest.revision, title: title, text: text, xFormat: isX ? format : nil), workspaceID: workspaceID) |
| 2722 | baseTitle = title; baseText = text; baseFormat = format |
| 2723 | library.storeNewsletterRecovery(nil, key: recoveryKey) |
| 2724 | message = nil |
| 2725 | return true |
| 2726 | } catch { message = error.localizedDescription; return false } |
| 2727 | } |
| 2728 | } |
| 2729 | |
| 2730 | private struct MobileAttachmentLabel: View { |
| 2731 | let attachment: CompanionLibrary.Item.Attachment |
| 2732 | |
| 2733 | var body: some View { |
| 2734 | Label(attachment == .video ? "Video attached" : "Image attached", |
| 2735 | systemImage: attachment == .video ? "video" : "photo") |
| 2736 | .foregroundStyle(.secondary) |
| 2737 | } |
| 2738 | } |
| 2739 | |
| 2740 | struct MobilePostImage: View { |
| 2741 | let data: Data? |
| 2742 | let label: String |
| 2743 | let identifier: String |
| 2744 | var thumbnail = false |
| 2745 | |
| 2746 | var body: some View { |
| 2747 | if let data, let image = UIImage(data: data) { |
| 2748 | let artwork = Image(uiImage: image).resizable() |
| 2749 | Group { |
| 2750 | if thumbnail { |
| 2751 | artwork.scaledToFill().frame(width: 56, height: 56) |
| 2752 | } else { |
| 2753 | artwork.scaledToFit().frame(maxWidth: 480, maxHeight: 340, alignment: .leading) |
| 2754 | } |
| 2755 | } |
| 2756 | .clipShape(.rect(cornerRadius: thumbnail ? 8 : 10)) |
| 2757 | .accessibilityLabel(label) |
| 2758 | .accessibilityIdentifier(identifier) |
| 2759 | } |
| 2760 | } |
| 2761 | } |
| 2762 | |
| 2763 | enum IdeaMediaPlatform: String, Identifiable { |
| 2764 | case tiktok, instagram |
| 2765 | var id: String { rawValue } |
| 2766 | } |
| 2767 | |
| 2768 | struct MobileReviewDetail: View { |
| 2769 | let item: CompanionLibrary.Item |
| 2770 | let library: MobileLibrary |
| 2771 | let workspaceID: UUID |
| 2772 | @Environment(\.studioPalette) private var palette |
| 2773 | @Environment(\.mobileWideLayout) private var wideLayout |
| 2774 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 2775 | @State private var note = "" |
| 2776 | @State private var message: String? |
| 2777 | @State private var savedNoteID: UUID? |
| 2778 | @State private var composingRevisionRequest = false |
| 2779 | @State private var showsOutline = false |
| 2780 | @State private var editingDraft = false |
| 2781 | @State private var choosingSchedule = false |
| 2782 | @State private var draftingIdea = false |
| 2783 | @State private var queuedDraftPlatforms: [String] = [] |
| 2784 | @State private var queuedWritingProvider = "Claude" |
| 2785 | @State private var viewingIdeaDraftID: String? |
| 2786 | @State private var mediaPlatform: IdeaMediaPlatform? |
| 2787 | @State private var editingIdeaImage = false |
| 2788 | @State private var ideaImagePrompt = "" |
| 2789 | @State private var needsMacUpdate = false |
| 2790 | @State private var confirmDeletion = false |
| 2791 | @State private var editBodyFirst = false |
| 2792 | @Environment(\.dismiss) private var dismiss |
| 2793 | @FocusState private var editingNote: Bool |
| 2794 | |
| 2795 | private var hasPendingChange: Bool { |
| 2796 | library.pendingChanges(for: item.id).contains { !([CompanionLibrary.Change.Action.note, .saveRevision].contains($0.action)) && $0.error == nil } |
| 2797 | || library.snapshot?.pending.contains { $0.itemID == item.id && !([CompanionLibrary.Change.Action.note, .saveRevision].contains($0.action)) } == true |
| 2798 | } |
| 2799 | |
| 2800 | private var pendingEdit: CompanionLibraryOutbox.Entry? { |
| 2801 | library.pendingChanges(for: item.id).last { [.editDraft, .editIdea].contains($0.action) } |
| 2802 | } |
| 2803 | |
| 2804 | private var ideaDraftRequest: CompanionLibraryOutbox.Entry? { |
| 2805 | library.pendingChanges(for: item.id).last { $0.ideaDraftPlatforms != nil } |
| 2806 | } |
| 2807 | |
| 2808 | private var hasPendingIdeaDraft: Bool { |
| 2809 | (ideaDraftRequest.map { $0.error == nil } ?? false) |
| 2810 | || library.snapshot?.pending.contains { $0.itemID == item.id && $0.ideaDraftPlatforms != nil } == true |
| 2811 | } |
| 2812 | |
| 2813 | private var ideaImageRequest: CompanionLibraryOutbox.Entry? { |
| 2814 | library.pendingChanges(for: item.id).last { $0.ideaImagePrompt != nil } |
| 2815 | } |
| 2816 | |
| 2817 | private var hasPendingIdeaImage: Bool { |
| 2818 | (ideaImageRequest.map { $0.error == nil } ?? false) |
| 2819 | || library.snapshot?.pending.contains { $0.itemID == item.id && $0.ideaImagePrompt != nil } == true |
| 2820 | } |
| 2821 | |
| 2822 | private var linkedIdeaDrafts: [CompanionLibrary.Item] { |
| 2823 | guard item.kind == .idea, let links = item.draftedIdeaIDs else { return [] } |
| 2824 | let drafts = library.visibleItems + (library.snapshot?.newsletters ?? []) + library.visibleScripts |
| 2825 | return CompanionLibrary.draftPlatforms(hasIdeaImage: true).compactMap { platform in |
| 2826 | drafts.first { $0.id == links[platform] && $0.isTrashed != true && !["published", "posted", "posting"].contains($0.status) |
| 2827 | && ($0.publicationURL ?? "").isEmpty } |
| 2828 | } |
| 2829 | } |
| 2830 | |
| 2831 | private var inTrash: Bool { item.isTrashed == true } |
| 2832 | |
| 2833 | private var canRequestRevision: Bool { |
| 2834 | guard !inTrash, !item.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false } |
| 2835 | return item.kind == .idea ? item.status == "draft" : ["", "draft", "ready"].contains(item.status) |
| 2836 | } |
| 2837 | |
| 2838 | private var canChooseSchedule: Bool { |
| 2839 | item.kind == .draft && !inTrash && !["queued", "due", "posting", "posted", "uncertain"].contains(item.status) |
| 2840 | && !item.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| 2841 | } |
| 2842 | |
| 2843 | private var postingWindow: CompanionPostingWindow? { |
| 2844 | guard item.requiresMacScheduling != true else { return nil } |
| 2845 | return library.snapshot?.postingWindows?[item.reviewPlatform] |
| 2846 | } |
| 2847 | |
| 2848 | private var showsScheduleAction: Bool { |
| 2849 | guard canChooseSchedule, item.requiresMacScheduling != true else { return false } |
| 2850 | if library.snapshot?.postingWindows != nil { return postingWindow != nil } |
| 2851 | return ["x", "linkedin", "instagram", "reddit"].contains(item.reviewPlatform) |
| 2852 | } |
| 2853 | |
| 2854 | private var schedulingRequest: MobileLibrary.SchedulingRequest? { |
| 2855 | library.pendingSchedules.first { $0.item.id == item.id } |
| 2856 | } |
| 2857 | |
| 2858 | private func date(_ timestamp: String) -> Date? { |
| 2859 | try? Date(timestamp, strategy: .iso8601.time(includingFractionalSeconds: true)) |
| 2860 | } |
| 2861 | |
| 2862 | var body: some View { |
| 2863 | if showsOutline { |
| 2864 | MobilePlanSection(item: item, library: library, workspaceID: workspaceID) { showsOutline = false } |
| 2865 | } else { |
| 2866 | document |
| 2867 | } |
| 2868 | } |
| 2869 | |
| 2870 | private var document: some View { |
| 2871 | Group { |
| 2872 | if let draft = linkedIdeaDrafts.first(where: { $0.id == viewingIdeaDraftID }) { |
| 2873 | if draft.isLongForm { |
| 2874 | MobileNewsletterDetail(item: draft, metadata: reviewPlatformName(draft.reviewPlatform), |
| 2875 | library: library, workspaceID: workspaceID) |
| 2876 | .toolbar { |
| 2877 | ToolbarItem(placement: .topBarLeading) { |
| 2878 | Button("Back to idea", systemImage: "chevron.left") { viewingIdeaDraftID = nil } |
| 2879 | } |
| 2880 | } |
| 2881 | } else { |
| 2882 | MobileItemEditor(item: draft, library: library, workspaceID: workspaceID, |
| 2883 | close: { viewingIdeaDraftID = nil }) |
| 2884 | .id(draft.id) |
| 2885 | } |
| 2886 | } else if editingDraft { |
| 2887 | MobileItemEditor(item: item, library: library, workspaceID: workspaceID, bodyFirst: editBodyFirst, close: { editingDraft = false }) |
| 2888 | } else { |
| 2889 | ScrollViewReader { scroll in |
| 2890 | preview.safeAreaInset(edge: .top, spacing: 0) { |
| 2891 | if !queuedDraftPlatforms.isEmpty && !draftingIdea { |
| 2892 | ideaDraftConfirmation { |
| 2893 | if let draft = linkedIdeaDrafts.first(where: { queuedDraftPlatforms.contains($0.reviewPlatform) }) { |
| 2894 | viewingIdeaDraftID = draft.id |
| 2895 | } else { |
| 2896 | withAnimation { scroll.scrollTo("idea.draft.source", anchor: .top) } |
| 2897 | } |
| 2898 | queuedDraftPlatforms = [] |
| 2899 | } |
| 2900 | } |
| 2901 | } |
| 2902 | } |
| 2903 | } |
| 2904 | } |
| 2905 | } |
| 2906 | |
| 2907 | private func ideaDraftConfirmation(view: @escaping () -> Void) -> some View { |
| 2908 | let layout = dynamicTypeSize.isAccessibilitySize |
| 2909 | ? AnyLayout(VStackLayout(alignment: .leading, spacing: 4)) |
| 2910 | : AnyLayout(HStackLayout(spacing: 12)) |
| 2911 | return layout { |
| 2912 | Label("Sent to \(queuedWritingProvider)", systemImage: "checkmark.circle.fill") |
| 2913 | .frame(maxWidth: .infinity, alignment: .leading) |
| 2914 | HStack(spacing: 12) { |
| 2915 | Button("View Post", action: view).fixedSize() |
| 2916 | .accessibilityIdentifier("idea.draft.viewPost") |
| 2917 | Button("Dismiss", systemImage: "xmark") { queuedDraftPlatforms = [] } |
| 2918 | .labelStyle(.iconOnly) |
| 2919 | } |
| 2920 | } |
| 2921 | .font(.subheadline.weight(.semibold)) |
| 2922 | .padding(.horizontal, 14) |
| 2923 | .padding(.vertical, 6) |
| 2924 | .studioSurface() |
| 2925 | .padding(.horizontal, 16) |
| 2926 | .padding(.vertical, 6) |
| 2927 | .background(palette.canvas) |
| 2928 | } |
| 2929 | |
| 2930 | private var preview: some View { |
| 2931 | Form { |
| 2932 | if inTrash { |
| 2933 | Section { |
| 2934 | Button("Restore", systemImage: "arrow.uturn.backward") { |
| 2935 | if save(.init(action: .restoreItem, itemID: item.id, revision: item.revision)), !wideLayout { dismiss() } |
| 2936 | } |
| 2937 | .disabled(hasPendingChange) |
| 2938 | Button(role: .destructive) { confirmDeletion = true } label: { |
| 2939 | Label("Delete permanently…", systemImage: "trash") |
| 2940 | .labelStyle(.titleAndIcon) |
| 2941 | .foregroundStyle(palette.theme == .paper ? palette.danger : Color.red) |
| 2942 | } |
| 2943 | .disabled(!library.canDelete(item.id)) |
| 2944 | .modifier(MobilePermanentDeletionConfirmation( |
| 2945 | isPresented: $confirmDeletion, |
| 2946 | message: "This cannot be undone." |
| 2947 | ) { remove(.deleteItem) }) |
| 2948 | } header: { |
| 2949 | Text(item.kind == .draft ? "Draft in Trash" : "Idea in Trash") |
| 2950 | } |
| 2951 | .listRowBackground(palette.card) |
| 2952 | } |
| 2953 | Section { |
| 2954 | if inTrash { |
| 2955 | Text(pendingEdit?.title ?? item.title) |
| 2956 | .font(.headline).foregroundStyle(palette.text) |
| 2957 | } else { |
| 2958 | Button { editBodyFirst = false; editingDraft = true } label: { |
| 2959 | Text(pendingEdit?.title ?? item.title) |
| 2960 | .font(.headline).foregroundStyle(palette.text) |
| 2961 | .frame(maxWidth: .infinity, alignment: .leading) |
| 2962 | } |
| 2963 | .buttonStyle(.plain) |
| 2964 | .accessibilityHint("Edit title") |
| 2965 | .accessibilityIdentifier(item.kind == .idea ? "idea.detail.title" : "draft.detail.title") |
| 2966 | .id("idea.draft.source") |
| 2967 | } |
| 2968 | if !inTrash && item.kind == .idea { |
| 2969 | if let error = ideaDraftRequest?.error { |
| 2970 | Label(error, systemImage: "exclamationmark.icloud").font(.footnote) |
| 2971 | } else if hasPendingIdeaDraft { |
| 2972 | let provider = ideaDraftRequest?.writingSelection?.provider ?? library.snapshot?.pending |
| 2973 | .first(where: { $0.itemID == item.id && $0.ideaDraftPlatforms != nil })?.writingSelection?.provider |
| 2974 | let name = library.snapshot?.writingProviders?.first { $0.id == provider }?.name ?? queuedWritingProvider |
| 2975 | Label("Queued for \(name) on your Mac.", systemImage: "clock").font(.footnote) |
| 2976 | } |
| 2977 | ForEach(linkedIdeaDrafts) { draft in |
| 2978 | Button { |
| 2979 | viewingIdeaDraftID = draft.id |
| 2980 | } label: { |
| 2981 | VStack(alignment: .leading, spacing: 3) { |
| 2982 | Label("View \(reviewPlatformName(draft.reviewPlatform)) draft", systemImage: "arrow.up.right") |
| 2983 | MobileLastUpdated(date: library.lastUpdated(draft)) |
| 2984 | } |
| 2985 | } |
| 2986 | .accessibilityIdentifier("idea.draft.link.\(draft.reviewPlatform)") |
| 2987 | } |
| 2988 | } |
| 2989 | if !item.platform.isEmpty { |
| 2990 | StudioPlatformLabel(name: item.reviewPlatform, title: reviewPlatformName(item.reviewPlatform)) |
| 2991 | .foregroundStyle(palette.muted) |
| 2992 | } |
| 2993 | MobilePostImage(data: item.imagePreview, label: item.kind == .idea ? "Post idea image" : "Draft image", |
| 2994 | identifier: item.kind == .idea ? "idea.image.preview" : "draft.image.preview") |
| 2995 | if let attachment = item.attachment, attachment == .video || item.imagePreview == nil { |
| 2996 | MobileAttachmentLabel(attachment: attachment) |
| 2997 | } |
| 2998 | if let reference = item.referenceID { |
| 2999 | StudioCopyReference(reference: reference) |
| 3000 | } |
| 3001 | if let updatedAt = library.lastUpdated(item) { |
| 3002 | Text("Last updated \(updatedAt.formatted(date: .abbreviated, time: .standard))") |
| 3003 | .font(.footnote) |
| 3004 | .foregroundStyle(palette.muted) |
| 3005 | .accessibilityIdentifier("post.lastUpdated") |
| 3006 | } |
| 3007 | NavigationLink { |
| 3008 | MobileRevisionHistory(item: item, library: library, workspaceID: workspaceID) |
| 3009 | } label: { Label("Revision history", systemImage: "clock.arrow.circlepath") } |
| 3010 | .accessibilityIdentifier("history.open") |
| 3011 | if item.shortened && pendingEdit == nil { |
| 3012 | Text("Waiting for the full text to sync.").font(.footnote).foregroundStyle(.secondary) |
| 3013 | } else if inTrash { |
| 3014 | Text(pendingEdit?.text ?? item.body).foregroundStyle(palette.text).textSelection(.enabled) |
| 3015 | } else if item.platform == "x", ["followup", "thread"].contains(pendingEdit?.xFormat ?? item.format ?? "") { |
| 3016 | let posts = XThreadText.posts(in: pendingEdit?.text ?? item.body) |
| 3017 | ForEach(posts.indices, id: \.self) { index in |
| 3018 | Button { |
| 3019 | editBodyFirst = true |
| 3020 | editingDraft = true |
| 3021 | } label: { |
| 3022 | VStack(alignment: .leading, spacing: 7) { |
| 3023 | Label(index == 0 ? "Opening post" : "Follow-up reply \(index)", systemImage: index == 0 ? "text.bubble" : "arrow.turn.down.right") |
| 3024 | .font(.subheadline.weight(.semibold)).foregroundStyle(palette.iconAccent) |
| 3025 | Text(XReplyArticle(posts[index]).copy).font(.body).foregroundStyle(palette.text) |
| 3026 | .frame(maxWidth: .infinity, alignment: .leading) |
| 3027 | } |
| 3028 | .padding(.vertical, 8) |
| 3029 | } |
| 3030 | .buttonStyle(.plain) |
| 3031 | .accessibilityIdentifier("x.reply.\(index)") |
| 3032 | if let ref = XReplyArticle(posts[index]).reference { |
| 3033 | if let article = library.snapshot?.articles?.first(where: { $0.platform != "linkedin" && $0.projectID == item.projectID && $0.referenceID == ref }) { |
| 3034 | NavigationLink { |
| 3035 | MobileNewsletterDetail(item: article, metadata: article.referenceID ?? "", library: library, workspaceID: workspaceID) |
| 3036 | } label: { Label("X article · " + article.title, systemImage: "doc.text") } |
| 3037 | if article.publicationURL?.isEmpty != false { Text("Publish the article first to include its X link.").font(.footnote).foregroundStyle(palette.muted) } |
| 3038 | } else { Text("Linked X article unavailable · " + ref).font(.footnote) } |
| 3039 | } |
| 3040 | } |
| 3041 | } else { |
| 3042 | Button { editBodyFirst = true; editingDraft = true } label: { |
| 3043 | Text(pendingEdit?.text ?? item.body) |
| 3044 | .font(.body).foregroundStyle(palette.text) |
| 3045 | .frame(maxWidth: .infinity, alignment: .leading) |
| 3046 | .contentShape(Rectangle()) |
| 3047 | } |
| 3048 | .buttonStyle(.plain) |
| 3049 | .accessibilityHint("Edit text") |
| 3050 | } |
| 3051 | if let error = pendingEdit?.error { |
| 3052 | Label(error, systemImage: "exclamationmark.icloud").font(.footnote) |
| 3053 | } |
| 3054 | if let status = item.generationStatus { Text(status).font(.footnote).foregroundStyle(palette.muted) } |
| 3055 | |
| 3056 | } |
| 3057 | .listRowBackground(palette.card) |
| 3058 | if !library.planText(item).isEmpty { |
| 3059 | Button("View outline", systemImage: "list.bullet.clipboard") { showsOutline = true } |
| 3060 | .font(.callout) |
| 3061 | .accessibilityIdentifier("outline.view") |
| 3062 | .listRowBackground(palette.card) |
| 3063 | } |
| 3064 | if !inTrash, (canRequestRevision && library.canUseAgentFeatures) || !library.revisionRequests(for: item).isEmpty { |
| 3065 | Section { |
| 3066 | if canRequestRevision && library.canUseAgentFeatures { |
| 3067 | if composingRevisionRequest { |
| 3068 | TextField(StudioRevisionRequestCopy.field, text: $note, |
| 3069 | prompt: Text(item.kind == .idea ? StudioRevisionRequestCopy.ideaExample : StudioRevisionRequestCopy.draftExample), |
| 3070 | axis: .vertical) |
| 3071 | .lineLimit(2...5) |
| 3072 | .focused($editingNote) |
| 3073 | .accessibilityIdentifier("review.revisionRequest") |
| 3074 | HStack { |
| 3075 | Button("Cancel") { |
| 3076 | editingNote = false |
| 3077 | composingRevisionRequest = false |
| 3078 | }.buttonStyle(.borderless) |
| 3079 | Spacer() |
| 3080 | Button(StudioRevisionRequestCopy.send) { |
| 3081 | if saveNote() { |
| 3082 | editingNote = false |
| 3083 | composingRevisionRequest = false |
| 3084 | } |
| 3085 | } |
| 3086 | .buttonStyle(.borderless) |
| 3087 | .disabled(note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || note.utf16.count > 1000) |
| 3088 | } |
| 3089 | if note.utf16.count > 1000 { |
| 3090 | Text("Use up to 1,000 characters.").font(.footnote).foregroundStyle(.secondary) |
| 3091 | } |
| 3092 | } else { |
| 3093 | Button(StudioRevisionRequestCopy.add, systemImage: "plus") { |
| 3094 | composingRevisionRequest = true |
| 3095 | } |
| 3096 | .accessibilityIdentifier("review.addRevisionRequest") |
| 3097 | } |
| 3098 | } |
| 3099 | ForEach(library.revisionRequests(for: item)) { request in |
| 3100 | StudioRevisionRequestRow(request: request) |
| 3101 | } |
| 3102 | if let savedNoteID, library.revisionRequests(for: item).contains(where: { |
| 3103 | $0.id == savedNoteID.uuidString.lowercased() && ($0.withdraw != nil || $0.state == StudioRevisionRequestCopy.actedOn) |
| 3104 | }) { |
| 3105 | let entry = library.pendingChanges(for: item.id).first { $0.id == savedNoteID } |
| 3106 | let uploaded = entry == nil || library.snapshot?.pending.contains { $0.id == savedNoteID } == true |
| 3107 | if entry?.error == nil { |
| 3108 | Label(uploaded ? "Revision request synced" : "Revision request saved · iCloud sync pending", |
| 3109 | systemImage: "checkmark") |
| 3110 | .font(.footnote).foregroundStyle(.secondary) |
| 3111 | } |
| 3112 | } |
| 3113 | if let error = item.writingError { |
| 3114 | Label(error, systemImage: "exclamationmark.icloud").font(.footnote) |
| 3115 | } |
| 3116 | } header: { |
| 3117 | Text(StudioRevisionRequestCopy.heading) |
| 3118 | } footer: { |
| 3119 | if canRequestRevision { |
| 3120 | Text(library.canUseAgentFeatures |
| 3121 | ? "Inkspring on your Mac applies the request using its writing connection. The earlier version stays in revision history." |
| 3122 | : "Connect a writing agent in Inkspring on your Mac to send a revision request.") |
| 3123 | } |
| 3124 | } |
| 3125 | .listRowBackground(palette.card) |
| 3126 | } |
| 3127 | if showsScheduleAction || canChooseSchedule && schedulingRequest != nil { |
| 3128 | Section { |
| 3129 | if showsScheduleAction { |
| 3130 | Button("Schedule post…", systemImage: "calendar.badge.clock", action: openSchedule) |
| 3131 | .disabled(hasPendingChange) |
| 3132 | .accessibilityIdentifier("review.schedulePost") |
| 3133 | } |
| 3134 | if let request = schedulingRequest { |
| 3135 | Label(request.error ?? "Waiting for your Mac to schedule this post.", |
| 3136 | systemImage: request.error == nil ? "clock" : "exclamationmark.icloud") |
| 3137 | .font(.footnote).foregroundStyle(.secondary) |
| 3138 | } |
| 3139 | } |
| 3140 | .listRowBackground(palette.card) |
| 3141 | } |
| 3142 | if item.isTrashed != true, item.kind == .idea, ["draft", "skipped"].contains(item.status) { |
| 3143 | if item.status == "draft", item.revision != "pending-add", library.snapshot?.supportsIdeaImages == true { |
| 3144 | Section { |
| 3145 | Button(item.attachment == .image ? "Regenerate image…" : "Generate image…", systemImage: "sparkles") { |
| 3146 | ideaImagePrompt = "" |
| 3147 | editingIdeaImage = true |
| 3148 | } |
| 3149 | .disabled(hasPendingChange || hasPendingIdeaImage || hasPendingIdeaDraft || library.snapshot?.ideaImageProvider == nil) |
| 3150 | .accessibilityIdentifier("idea.image.open") |
| 3151 | if let error = ideaImageRequest?.error { |
| 3152 | Label(error, systemImage: "exclamationmark.icloud").font(.footnote) |
| 3153 | } else if hasPendingIdeaImage { |
| 3154 | Label("Queued for image generation on your Mac.", systemImage: "clock").font(.footnote) |
| 3155 | } |
| 3156 | } footer: { |
| 3157 | if library.snapshot?.ideaImageProvider == nil { Text("Add an image API key in Inkspring on your Mac.") } |
| 3158 | } |
| 3159 | .listRowBackground(palette.card) |
| 3160 | } |
| 3161 | if item.status == "draft", item.revision != "pending-add", library.snapshot?.supportsMediaDrafts == true { |
| 3162 | Section { |
| 3163 | Menu("Create media draft", systemImage: "photo.on.rectangle") { |
| 3164 | Button("TikTok video") { mediaPlatform = .tiktok } |
| 3165 | Button("Instagram post") { mediaPlatform = .instagram } |
| 3166 | } |
| 3167 | .accessibilityIdentifier("idea.media.open") |
| 3168 | } |
| 3169 | .listRowBackground(palette.card) |
| 3170 | } |
| 3171 | Section { |
| 3172 | if item.status == "draft", library.canUseAgentFeatures { |
| 3173 | Button { |
| 3174 | queuedDraftPlatforms = [] |
| 3175 | draftingIdea = true |
| 3176 | } label: { |
| 3177 | Label("Draft from post idea", systemImage: "square.and.pencil") |
| 3178 | } |
| 3179 | .buttonStyle(MobilePrimaryActionStyle()) |
| 3180 | .disabled(hasPendingChange || hasPendingIdeaDraft || hasPendingIdeaImage || item.revision == "pending-add" |
| 3181 | || CompanionLibrary.draftPlatforms(hasIdeaImage: item.attachment == .image) |
| 3182 | .allSatisfy { item.draftedIdeaPlatforms?.contains($0) == true }) |
| 3183 | .accessibilityIdentifier("idea.draft.open") |
| 3184 | } |
| 3185 | Button(item.status == "draft" ? "Skip idea" : "Restore idea") { |
| 3186 | save(.init(action: item.status == "draft" ? .skipIdea : .restoreIdea, |
| 3187 | itemID: item.id, revision: item.revision)) |
| 3188 | } |
| 3189 | .disabled(library.busy || hasPendingChange) |
| 3190 | } |
| 3191 | .listRowBackground(palette.card) |
| 3192 | } |
| 3193 | if hasPendingChange { Text("iCloud sync in progress.").foregroundStyle(.secondary) } |
| 3194 | if let message { Text(message).foregroundStyle(.secondary) } |
| 3195 | } |
| 3196 | .scrollContentBackground(.hidden) |
| 3197 | .navigationTitle(inTrash ? "Trash" : item.kind == .draft ? "Draft" : "Idea") |
| 3198 | .navigationBarTitleDisplayMode(.inline) |
| 3199 | .toolbar { |
| 3200 | ToolbarItemGroup(placement: .topBarTrailing) { |
| 3201 | if item.isTrashed != true { |
| 3202 | Button("Edit", systemImage: "pencil") { editingDraft = true } |
| 3203 | } |
| 3204 | moreActions |
| 3205 | } |
| 3206 | } |
| 3207 | .onChange(of: library.canUseAgentFeatures) { |
| 3208 | if !library.canUseAgentFeatures { draftingIdea = false } |
| 3209 | } |
| 3210 | .sheet(isPresented: $editingIdeaImage) { |
| 3211 | NavigationStack { |
| 3212 | Form { |
| 3213 | Section { |
| 3214 | TextField("Image direction (optional)", text: $ideaImagePrompt, axis: .vertical) |
| 3215 | .lineLimit(3...7) |
| 3216 | } footer: { |
| 3217 | Text("Your Mac generates the image for this idea. It syncs here when it’s ready.") |
| 3218 | } |
| 3219 | .listRowBackground(palette.card) |
| 3220 | } |
| 3221 | .scrollContentBackground(.hidden) |
| 3222 | .background(palette.canvas) |
| 3223 | .navigationTitle("Idea image").navigationBarTitleDisplayMode(.inline) |
| 3224 | .toolbar { |
| 3225 | ToolbarItem(placement: .cancellationAction) { Button("Cancel") { editingIdeaImage = false } } |
| 3226 | ToolbarItem(placement: .confirmationAction) { |
| 3227 | Button("Generate") { |
| 3228 | var change = CompanionLibrary.Change(action: .note, itemID: item.id, revision: item.revision) |
| 3229 | change.ideaImagePrompt = ideaImagePrompt |
| 3230 | if save(change) { editingIdeaImage = false } |
| 3231 | } |
| 3232 | .disabled(ideaImagePrompt.utf16.count > 4000) |
| 3233 | .accessibilityIdentifier("idea.image.generate") |
| 3234 | } |
| 3235 | } |
| 3236 | } |
| 3237 | } |
| 3238 | .sheet(isPresented: $draftingIdea, onDismiss: { |
| 3239 | if !queuedDraftPlatforms.isEmpty { AccessibilityNotification.Announcement("Sent to \(queuedWritingProvider)").post() } |
| 3240 | }) { |
| 3241 | NavigationStack { |
| 3242 | MobileIdeaDraftPicker(item: item, library: library, workspaceID: workspaceID) { platforms, provider in |
| 3243 | queuedDraftPlatforms = platforms |
| 3244 | queuedWritingProvider = provider |
| 3245 | draftingIdea = false |
| 3246 | } |
| 3247 | .toolbar { Button("Done") { draftingIdea = false } } |
| 3248 | } |
| 3249 | } |
| 3250 | .sheet(item: $mediaPlatform) { platform in |
| 3251 | NavigationStack { |
| 3252 | MobileMediaDraftForm(platform: platform.rawValue, library: library, initialProject: item.projectID, ideaID: item.id) |
| 3253 | } |
| 3254 | } |
| 3255 | .sheet(isPresented: $choosingSchedule) { |
| 3256 | if let postingWindow { |
| 3257 | let zone = library.snapshot?.postingTimeZone.flatMap(TimeZone.init(identifier:)) ?? .current |
| 3258 | MobileSchedulePicker(item: item, window: postingWindow, timeZone: zone) { hour in |
| 3259 | try library.saveChange(.init(action: .scheduleDraft, itemID: item.id, revision: item.revision, |
| 3260 | text: hour.formatted(.iso8601)), workspaceID: workspaceID) |
| 3261 | } |
| 3262 | } |
| 3263 | } |
| 3264 | .alert("Schedule from this device", isPresented: $needsMacUpdate) { |
| 3265 | Button("OK", role: .cancel) {} |
| 3266 | } message: { |
| 3267 | Text("Your Mac handles scheduled posts. You can schedule this draft from Schedule in Inkspring on your Mac. To schedule from this device, update and open Inkspring on your Mac, then refresh Review here.") |
| 3268 | } |
| 3269 | } |
| 3270 | |
| 3271 | private func openSchedule() { |
| 3272 | if postingWindow != nil { choosingSchedule = true } |
| 3273 | else { needsMacUpdate = true } |
| 3274 | } |
| 3275 | |
| 3276 | private var moreActions: some View { |
| 3277 | Menu { |
| 3278 | if !inTrash { |
| 3279 | if library.snapshot?.supportsContentPlans == true { |
| 3280 | Button(library.planText(item).isEmpty ? "Add outline" : "View outline", systemImage: "list.bullet.clipboard") { showsOutline = true } |
| 3281 | .accessibilityIdentifier("outline.menu") |
| 3282 | } |
| 3283 | Button("Edit title", systemImage: "pencil") { editBodyFirst = false; editingDraft = true } |
| 3284 | Button("Edit text", systemImage: "square.and.pencil") { editBodyFirst = true; editingDraft = true } |
| 3285 | if showsScheduleAction { |
| 3286 | Button("Schedule post…", systemImage: "calendar.badge.clock", action: openSchedule) |
| 3287 | .disabled(hasPendingChange) |
| 3288 | } |
| 3289 | } |
| 3290 | Button("Copy text", systemImage: "doc.on.doc") { UIPasteboard.general.string = pendingEdit?.text ?? item.body } |
| 3291 | .disabled(item.shortened && pendingEdit == nil) |
| 3292 | ShareLink(item: pendingEdit?.text ?? item.body) { Label("Share text", systemImage: "square.and.arrow.up") } |
| 3293 | if !inTrash { |
| 3294 | Button(item.kind == .idea ? "Skip idea" : "Move to Trash", systemImage: "trash", role: .destructive) { remove(.trashItem) } |
| 3295 | .disabled(hasPendingChange) |
| 3296 | } |
| 3297 | } label: { Image(systemName: "ellipsis").frame(width: 32, height: 32) } |
| 3298 | .accessibilityLabel("More actions") |
| 3299 | } |
| 3300 | |
| 3301 | private func remove(_ action: CompanionLibrary.Change.Action) { |
| 3302 | if save(.init(action: action, itemID: item.id, revision: item.revision)), !wideLayout { dismiss() } |
| 3303 | } |
| 3304 | |
| 3305 | private func saveNote() -> Bool { |
| 3306 | let text = note.trimmingCharacters(in: .whitespacesAndNewlines) |
| 3307 | guard !text.isEmpty, text.utf16.count <= 1000 else { return false } |
| 3308 | let change = CompanionLibrary.Change(action: .note, itemID: item.id, revision: item.revision, |
| 3309 | text: text, requestsWritingHelp: true) |
| 3310 | if save(change) { |
| 3311 | note = "" |
| 3312 | savedNoteID = change.id |
| 3313 | return true |
| 3314 | } |
| 3315 | return false |
| 3316 | } |
| 3317 | |
| 3318 | @discardableResult |
| 3319 | private func save(_ change: CompanionLibrary.Change) -> Bool { |
| 3320 | do { |
| 3321 | try library.saveChange(change, workspaceID: workspaceID) |
| 3322 | message = nil |
| 3323 | InkspringReview.recordActivity() |
| 3324 | return true |
| 3325 | } catch { |
| 3326 | message = error.localizedDescription |
| 3327 | return false |
| 3328 | } |
| 3329 | } |
| 3330 | } |
| 3331 | |
| 3332 | private struct MobileRevisionHistory: View { |
| 3333 | let item: CompanionLibrary.Item |
| 3334 | let library: MobileLibrary |
| 3335 | let workspaceID: UUID |
| 3336 | @Environment(\.studioPalette) private var palette |
| 3337 | @State private var revisions: [ContentRevision] = [] |
| 3338 | @State private var message: String? |
| 3339 | |
| 3340 | var body: some View { |
| 3341 | List { |
| 3342 | Section { |
| 3343 | Text("Every save keeps a snapshot. Restoring creates a new version and keeps the later versions.") |
| 3344 | .font(.footnote).foregroundStyle(palette.muted) |
| 3345 | }.listRowBackground(palette.card) |
| 3346 | Section { |
| 3347 | ForEach(Array(revisions.enumerated()), id: \.element.id) { index, revision in |
| 3348 | NavigationLink { |
| 3349 | MobileRevisionDetail(item: item, revision: revision, library: library, workspaceID: workspaceID) |
| 3350 | } label: { |
| 3351 | VStack(alignment: .leading, spacing: 6) { |
| 3352 | Text(revision.date.map { $0.formatted(date: .abbreviated, time: .standard) } ?? "Earlier version") |
| 3353 | .font(.headline) |
| 3354 | Text(revision.source).font(.caption).foregroundStyle(palette.muted) |
| 3355 | Text(revision.title).font(.callout) |
| 3356 | Text(revision.text).font(.footnote).lineLimit(2).foregroundStyle(palette.muted) |
| 3357 | } |
| 3358 | }.accessibilityIdentifier("history.version.\(index)") |
| 3359 | } |
| 3360 | if revisions.isEmpty { Text("History starts with saves in this version of Inkspring.") } |
| 3361 | }.listRowBackground(palette.card) |
| 3362 | if let message { Text(message).foregroundStyle(palette.danger) } |
| 3363 | } |
| 3364 | .scrollContentBackground(.hidden).background(palette.canvas) |
| 3365 | .navigationTitle("Revision history").navigationBarTitleDisplayMode(.inline) |
| 3366 | .task(id: library.snapshot?.updatedAt) { |
| 3367 | do { revisions = try library.history(for: item) } |
| 3368 | catch { message = "Saved history couldn’t be read. \(error.localizedDescription)" } |
| 3369 | } |
| 3370 | } |
| 3371 | } |
| 3372 | |
| 3373 | private struct MobileRevisionDetail: View { |
| 3374 | let item: CompanionLibrary.Item |
| 3375 | let revision: ContentRevision |
| 3376 | let library: MobileLibrary |
| 3377 | let workspaceID: UUID |
| 3378 | @Environment(\.studioPalette) private var palette |
| 3379 | @Environment(\.dismiss) private var dismiss |
| 3380 | @State private var message: String? |
| 3381 | |
| 3382 | var body: some View { |
| 3383 | ScrollView { |
| 3384 | VStack(alignment: .leading, spacing: 18) { |
| 3385 | Text(revision.title).font(.title2.bold()) |
| 3386 | Text(revision.source).font(.footnote).foregroundStyle(palette.muted) |
| 3387 | if ["thread", "followup"].contains(revision.format ?? "") { |
| 3388 | let posts = XThreadText.posts(in: revision.text) |
| 3389 | ForEach(posts.indices, id: \.self) { index in |
| 3390 | Text(index == 0 ? "Opening post" : "Follow-up reply \(index)").font(.headline) |
| 3391 | Text(posts[index]).textSelection(.enabled) |
| 3392 | } |
| 3393 | } else if item.isLongForm { |
| 3394 | MobileNewsletterMarkdown(markdown: revision.text) |
| 3395 | } else { Text(revision.text).textSelection(.enabled) } |
| 3396 | Text("Your current version stays in history when you restore.").font(.footnote).foregroundStyle(palette.muted) |
| 3397 | Button("Restore this version", systemImage: "clock.arrow.circlepath") { |
| 3398 | do { |
| 3399 | let latest = ((library.snapshot?.items ?? []) + (library.snapshot?.newsletters ?? []) + (library.snapshot?.scripts ?? []) + (library.snapshot?.articles ?? [])) |
| 3400 | .first { $0.id == item.id } ?? item |
| 3401 | try library.saveChange(.init(action: .editDraft, itemID: latest.id, revision: latest.revision, |
| 3402 | title: revision.title, text: revision.text, editsNewsletter: latest.kind == .newsletter ? true : nil, |
| 3403 | baseNewsletterText: latest.isLongForm ? latest.body : nil, |
| 3404 | xFormat: latest.platform == "x" ? revision.format : nil, |
| 3405 | restoresRevision: true, subtitle: revision.subtitle, editsScript: [.script, .article].contains(latest.kind) ? true : nil, writingKind: latest.kind == .article ? "article" : nil), workspaceID: workspaceID) |
| 3406 | dismiss() |
| 3407 | } catch { message = error.localizedDescription } |
| 3408 | } |
| 3409 | .buttonStyle(.borderedProminent) |
| 3410 | .tint(palette.iconAccent) |
| 3411 | .disabled(item.isTrashed == true || library.isChanging(item.id) || |
| 3412 | ["posting", "posted", "uncertain", "published"].contains(item.status)) |
| 3413 | .accessibilityIdentifier("history.restore") |
| 3414 | if let message { Text(message).foregroundStyle(palette.danger) } |
| 3415 | } |
| 3416 | .font(.body).lineSpacing(5) |
| 3417 | .frame(maxWidth: .infinity, alignment: .leading) |
| 3418 | .padding(18).studioSurface().padding(16) |
| 3419 | } |
| 3420 | .background(palette.canvas).navigationTitle("Saved version").navigationBarTitleDisplayMode(.inline) |
| 3421 | } |
| 3422 | } |
| 3423 | |
| 3424 | private struct MobileSchedulePicker: View { |
| 3425 | let item: CompanionLibrary.Item |
| 3426 | let window: CompanionPostingWindow |
| 3427 | let timeZone: TimeZone |
| 3428 | let schedule: (Date) throws -> Void |
| 3429 | @Environment(\.dismiss) private var dismiss |
| 3430 | @Environment(\.studioPalette) private var palette |
| 3431 | @State private var day = Date.now |
| 3432 | @State private var selectedHour: Date? |
| 3433 | @State private var message: String? |
| 3434 | |
| 3435 | private var calendar: Calendar { |
| 3436 | var calendar = Calendar.current |
| 3437 | calendar.timeZone = timeZone |
| 3438 | return calendar |
| 3439 | } |
| 3440 | |
| 3441 | private var hours: [Date] { |
| 3442 | window.hours.compactMap { hour in |
| 3443 | guard let date = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day, matchingPolicy: .strict), |
| 3444 | calendar.isDate(date, inSameDayAs: day), date.addingTimeInterval(3600) > .now.addingTimeInterval(120) |
| 3445 | else { return nil } |
| 3446 | return date |
| 3447 | } |
| 3448 | } |
| 3449 | |
| 3450 | var body: some View { |
| 3451 | NavigationStack { |
| 3452 | Form { |
| 3453 | Section { |
| 3454 | Text(item.title).font(.headline) |
| 3455 | StudioPlatformLabel(name: item.reviewPlatform, title: reviewPlatformName(item.reviewPlatform)) |
| 3456 | } |
| 3457 | .listRowBackground(palette.card) |
| 3458 | Section("Posting day") { |
| 3459 | DatePicker("Posting day", selection: $day, in: calendar.startOfDay(for: .now)..., displayedComponents: .date) |
| 3460 | .datePickerStyle(.graphical) |
| 3461 | .labelsHidden() |
| 3462 | .accessibilityIdentifier("schedule.postingDay") |
| 3463 | } |
| 3464 | .listRowBackground(palette.card) |
| 3465 | Section { |
| 3466 | if hours.isEmpty { |
| 3467 | Text("Choose another day to see available posting hours.") |
| 3468 | .foregroundStyle(.secondary) |
| 3469 | } else { |
| 3470 | Picker("Posting hour", selection: $selectedHour) { |
| 3471 | ForEach(hours, id: \.self) { hour in |
| 3472 | Text(hour, format: Date.FormatStyle(date: .omitted, time: .shortened, timeZone: timeZone)) |
| 3473 | .tag(Optional(hour)) |
| 3474 | } |
| 3475 | } |
| 3476 | .accessibilityIdentifier("schedule.postingHour") |
| 3477 | } |
| 3478 | } footer: { |
| 3479 | Text("Uses your Mac’s posting hours (\(timeZone.identifier)). Your Mac chooses the posting minute and checks the time before scheduling.") |
| 3480 | } |
| 3481 | .listRowBackground(palette.card) |
| 3482 | if let message { Text(message).foregroundStyle(palette.danger) } |
| 3483 | } |
| 3484 | .environment(\.calendar, calendar) |
| 3485 | .environment(\.timeZone, timeZone) |
| 3486 | .scrollContentBackground(.hidden) |
| 3487 | .background(palette.canvas) |
| 3488 | .navigationTitle("Schedule post") |
| 3489 | .navigationBarTitleDisplayMode(.inline) |
| 3490 | .toolbar { |
| 3491 | ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } |
| 3492 | ToolbarItem(placement: .confirmationAction) { |
| 3493 | Button("Schedule") { |
| 3494 | guard let selectedHour, hours.contains(selectedHour) else { return } |
| 3495 | do { try schedule(selectedHour); dismiss() } |
| 3496 | catch { message = error.localizedDescription } |
| 3497 | } |
| 3498 | .disabled(selectedHour.map { !hours.contains($0) } ?? true) |
| 3499 | .accessibilityIdentifier("schedule.confirm") |
| 3500 | } |
| 3501 | } |
| 3502 | .onChange(of: hours, initial: true) { _, hours in |
| 3503 | if selectedHour.map({ hours.contains($0) }) != true { selectedHour = hours.first } |
| 3504 | } |
| 3505 | .onAppear { |
| 3506 | if hours.isEmpty, let tomorrow = calendar.date(byAdding: .day, value: 1, to: day) { day = tomorrow } |
| 3507 | } |
| 3508 | } |
| 3509 | } |
| 3510 | } |
| 3511 | |
| 3512 | private struct MobilePermanentDeletionConfirmation: ViewModifier { |
| 3513 | @Environment(\.studioPalette) private var palette |
| 3514 | @Binding var isPresented: Bool |
| 3515 | let message: String |
| 3516 | let remove: () -> Void |
| 3517 | |
| 3518 | func body(content: Content) -> some View { |
| 3519 | if palette.theme == .paper { |
| 3520 | content.popover(isPresented: $isPresented) { |
| 3521 | VStack(alignment: .leading, spacing: 12) { |
| 3522 | Text("Delete permanently?") |
| 3523 | .font(.headline) |
| 3524 | .accessibilityAddTraits(.isHeader) |
| 3525 | Text(message).font(.subheadline).foregroundStyle(palette.muted) |
| 3526 | Button("Delete permanently", role: .destructive) { |
| 3527 | remove() |
| 3528 | isPresented = false |
| 3529 | } |
| 3530 | .buttonStyle(.plain) |
| 3531 | .font(.subheadline.weight(.semibold)) |
| 3532 | .foregroundStyle(palette.accentText) |
| 3533 | .frame(maxWidth: .infinity, minHeight: 44) |
| 3534 | .background(palette.danger, in: Capsule()) |
| 3535 | Button("Cancel", role: .cancel) { isPresented = false } |
| 3536 | .buttonStyle(.plain) |
| 3537 | .font(.subheadline.weight(.medium)) |
| 3538 | .frame(maxWidth: .infinity, minHeight: 44) |
| 3539 | .background(palette.well, in: Capsule()) |
| 3540 | } |
| 3541 | .foregroundStyle(palette.text) |
| 3542 | .padding(18) |
| 3543 | .frame(idealWidth: 270, maxWidth: 340) |
| 3544 | .presentationBackground(palette.panel) |
| 3545 | .presentationDetents([.medium, .large]) |
| 3546 | } |
| 3547 | } else { |
| 3548 | content.confirmationDialog("Delete permanently?", |
| 3549 | isPresented: $isPresented, titleVisibility: .visible) { |
| 3550 | Button("Delete permanently", role: .destructive, action: remove) |
| 3551 | Button("Cancel", role: .cancel) {} |
| 3552 | } message: { |
| 3553 | Text(message) |
| 3554 | } |
| 3555 | } |
| 3556 | } |
| 3557 | } |