Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ScheduleView.swift

1import SwiftUI
2import InkspringSchedule
3
4struct ScheduleView: View {
5 @Environment(\.studioPalette) private var palette
6 let workspace: Workspace
7 let open: (WorkspaceRecord) -> Void
8 @Binding var focusDraftID: String?
9 @Binding var tab: ScheduleListing.Section
10 let revise: (WorkspaceRecord, @escaping (WorkspaceRecord) -> Void) -> Void
11 let reviewPublication: (WorkspaceRecord, Date?, @escaping (WorkspaceRecord) -> Void) -> Void
12 let chooseTime: (WorkspaceRecord, @escaping () -> Void) -> Void
13 let reviewNewsletter: (WorkspaceRecord, Bool, @escaping (WorkspaceRecord) -> Void) -> Void
14 @Environment(\.openURL) private var openURL
15 @Environment(\.scenePhase) private var scenePhase
16 @State private var projectFilter: String?
17 @State private var channelFilter: String?
18 @State private var manuallyPosted: WorkspaceRecord?
19 @State private var editingPublishedLink: WorkspaceRecord?
20 @State private var publishedLink = ""
21 @State private var cancellingNewsletter: WorkspaceRecord?
22 @State private var checkingNewsletter: WorkspaceRecord?
23 @State private var returningIdea: Workspace.IdeaReturnPlan?
24 @State private var generatingImages: Set<String> = []
25 @State private var changingNotifications = false
26 @State private var notificationsDenied = false
27 @State private var notificationError: String?
28
29 var body: some View {
30 let listing = ScheduleListing(records: workspace.records, projectID: projectFilter, channel: channelFilter)
31 let published = PublishedPostFeed.entries(in: workspace.records, projectID: projectFilter, channel: channelFilter)
32 let publishedIDs = Set(published.map(\.id))
33 let rows = tab == .history ? listing[.history].filter { !publishedIDs.contains($0.id) } : listing[tab]
34 let visibleFocus = focusDraftID.flatMap { id in
35 rows.contains { $0.id == id } || (tab == .history && publishedIDs.contains(id)) ? id : nil
36 }
37 let totals = projectFilter == nil && channelFilter == nil ? listing : ScheduleListing(records: workspace.records)
38 ScrollViewReader { proxy in
39 StudioScrollView {
40 VStack(alignment: .leading, spacing: 16) {
41 HStack {
42 PageHeading(title: tab == .history ? "Published" : "Schedule",
43 subtitle: tab == .history ? "Open a post to read and respond on its original platform."
44 : "Review drafts and check what’s going out.")
45 Spacer()
46 }
47 Label("\(totals[.scheduled].count) scheduled · \(totals[.ready].count) ready across all projects",
48 systemImage: "calendar")
49 .font(InkspringTypography.interface(13))
50 .frame(maxWidth: .infinity, alignment: .leading)
51 .padding(12)
52 .studioSurface()
53 HStack(spacing: 10) {
54 let projectName = workspace.projects.first { $0.id == projectFilter }?.title
55 StudioFilterMenu(title: "Filter by project", value: projectName ?? "All projects") {
56 Picker("Projects", selection: $projectFilter) {
57 Text("All projects").tag(nil as String?)
58 ForEach(workspace.projects) { project in Text(project.title).tag(Optional(project.id)) }
59 }
60 .pickerStyle(.inline)
61 }
62 StudioChoicePicker(title: "Filter by channel", selection: $channelFilter,
63 options: [nil] + SocialPlatform.allCases.map { Optional($0.rawValue) } + ["substack"],
64 label: { $0.map(platformName) ?? "All channels" },
65 icon: { $0.flatMap(PlatformMark.image) })
66 }
67 StudioTabs(selection: $tab, tabs: ScheduleListing.Section.allCases, label: { $0.rawValue },
68 count: { $0 == .history ? published.count : listing[$0].count })
69 if tab == .scheduled { postingControls }
70 if tab == .history {
71 ForEach(published) { post in publishedCard(post).id(post.id) }
72 }
73 if rows.isEmpty && (tab != .history || published.isEmpty) {
74 VStack(spacing: 10) {
75 Image(systemName: "calendar")
76 .font(.system(size: 26, weight: .medium))
77 .foregroundStyle(palette.muted)
78 .accessibilityHidden(true)
79 Text(emptyMessage)
80 .font(InkspringTypography.editorial(21))
81 if tab == .scheduled && !listing[.ready].isEmpty {
82 Button("See drafts ready to schedule") { tab = .ready }
83 .padding(.top, 4)
84 }
85 }
86 .frame(maxWidth: .infinity, minHeight: 144)
87 .studioSurface()
88 }
89 if tab == .history, !rows.isEmpty {
90 Text("Other activity").font(.headline)
91 }
92 ForEach(Array(rows.enumerated()), id: \.element.id) { index, draft in
93 let day = scheduledDay(draft)
94 if tab == .scheduled, index == 0 || day != scheduledDay(rows[index - 1]) {
95 Text(day?.formatted(date: .complete, time: .omitted) ?? "Time unavailable").font(.headline)
96 }
97 if draft.kind == "newsletter" {
98 newsletterCard(draft).id(draft.id)
99 } else {
100 draftCard(draft).id(draft.id)
101 }
102 }
103 if tab == .scheduled, channelFilter == nil || channelFilter == "x" {
104 XPostingHours(records: workspace.records)
105 }
106 }
107 .studioPage()
108 }
109 .task(id: focusDraftID) {
110 guard let id = focusDraftID,
111 let draft = workspace.records.first(where: { $0.id == id }),
112 let section = ScheduleListing.section(for: draft) else { return }
113 projectFilter = draft.projectID
114 channelFilter = nil
115 tab = section
116 }
117 .task(id: visibleFocus) {
118 guard let id = visibleFocus else { return }
119 await Task.yield()
120 guard !Task.isCancelled else { return }
121 proxy.scrollTo(id, anchor: .top)
122 focusDraftID = nil
123 }
124 }
125 .task(id: scenePhase) {
126 if scenePhase == .active { notificationsDenied = await ScheduleNotifications.isDenied() }
127 }
128 .confirmationDialog("Record this post as published?", isPresented: Binding(
129 get: { manuallyPosted != nil }, set: { if !$0 { manuallyPosted = nil } }
130 ), presenting: manuallyPosted) { draft in
131 Button("Record as posted") {
132 workspace.perform {
133 try update(draft, status: "posted")
134 tab = .history
135 }
136 }
137 } message: { draft in
138 Text("Use this for “\(draft.title)” after you’ve published it yourself.")
139 }
140 .alert("Add the published post link", isPresented: Binding(
141 get: { editingPublishedLink != nil }, set: { if !$0 { editingPublishedLink = nil } }
142 ), presenting: editingPublishedLink) { draft in
143 TextField("HTTPS post link", text: $publishedLink)
144 Button("Save link") {
145 workspace.perform { try workspace.savePublishedPostLink(draft, address: publishedLink) }
146 }
147 Button("Cancel", role: .cancel) {}
148 }
149 .confirmationDialog("Return this idea to the queue?", isPresented: Binding(
150 get: { returningIdea != nil }, set: { if !$0 { returningIdea = nil } }
151 ), presenting: returningIdea) { plan in
152 Button("Reopen idea") {
153 workspace.perform { try workspace.returnToIdeas(plan) }
154 }
155 } message: { plan in
156 Text("“\(plan.ideaTitle)” will appear in Open. Its drafts and publishing history stay saved.")
157 }
158 .confirmationDialog("Cancel the newsletter schedule?", isPresented: Binding(
159 get: { cancellingNewsletter != nil }, set: { if !$0 { cancellingNewsletter = nil } }
160 ), presenting: cancellingNewsletter) { item in
161 Button("Cancel schedule", role: .destructive) {
162 runNewsletterAction { try await Substack(workspace: workspace).cancel(item.id) }
163 }
164 } message: { _ in
165 Text("The newsletter stays saved as a draft on Substack.")
166 }
167 .confirmationDialog("Did you check the outcome in Substack?", isPresented: Binding(
168 get: { checkingNewsletter != nil }, set: { if !$0 { checkingNewsletter = nil } }
169 ), presenting: checkingNewsletter) { item in
170 Button("I checked Substack") {
171 runNewsletterAction { try await Substack(workspace: workspace).acknowledge(item.id) }
172 }
173 } message: { _ in
174 Text("Check your drafts, scheduled posts, and published posts before continuing.")
175 }
176 }
177
178 private var postingControls: some View {
179 VStack(alignment: .leading, spacing: 12) {
180 Toggle(isOn: Binding(get: {
181 workspace.settings["autoPost"] as? Bool == true
182 }, set: { enabled in
183 workspace.perform { try workspace.set("autoPost", to: enabled) }
184 })) {
185 postingLabel("Automatic posting",
186 description: "Send eligible scheduled posts from your Mac at their chosen time. Keep it off to review and publish posts yourself.")
187 }
188 .toggleStyle(.switch)
189 .accessibilityLabel("Automatic posting")
190 StudioRule()
191 Toggle(isOn: Binding(get: {
192 workspace.settings[ScheduleNotifications.settingKey] as? Bool == true && !notificationsDenied
193 }, set: changeScheduleNotifications)) {
194 postingLabel("Schedule notifications",
195 description: "Get an alert when a scheduled post needs attention while automatic posting is on.")
196 }
197 .toggleStyle(.switch)
198 .accessibilityLabel("Schedule notifications")
199 .disabled(changingNotifications)
200 if notificationsDenied {
201 Text("macOS has notifications turned off for Inkspring.")
202 .font(.callout).foregroundStyle(palette.muted)
203 Button("Open Notification Settings", systemImage: "gearshape") {
204 if let url = URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension") {
205 openURL(url)
206 }
207 }
208 }
209 if let notificationError { Text(notificationError).foregroundStyle(palette.danger) }
210 }
211 .padding(14)
212 .studioSurface()
213 }
214
215 private func postingLabel(_ title: String, description: String) -> some View {
216 VStack(alignment: .leading, spacing: 3) {
217 Text(title).font(.headline)
218 Text(description)
219 .font(.callout)
220 .foregroundStyle(palette.muted)
221 .fixedSize(horizontal: false, vertical: true)
222 }
223 .frame(maxWidth: .infinity, alignment: .leading)
224 }
225
226 private func changeScheduleNotifications(_ enabled: Bool) {
227 changingNotifications = true
228 notificationError = nil
229 Task {
230 defer { changingNotifications = false }
231 do { try await workspace.setScheduleNotifications(enabled) }
232 catch {
233 notificationsDenied = await ScheduleNotifications.isDenied()
234 if !notificationsDenied { notificationError = error.localizedDescription }
235 }
236 }
237 }
238
239 private func draftCard(_ draft: WorkspaceRecord) -> some View {
240 VStack(alignment: .leading, spacing: 8) {
241 RecordCard(record: draft)
242 HStack {
243 Text(projectName(for: draft)).foregroundStyle(.secondary)
244 if let date = ScheduleListing.date(for: draft, in: tab), tab != .ready {
245 Text(date.formatted(date: .abbreviated, time: .shortened))
246 }
247 if draft.scheduleStatus == "due" { Text("Ready for review").foregroundStyle(.secondary) }
248 if draft.scheduleStatus == "posting" { Text("Sending").foregroundStyle(.secondary) }
249 if draft.scheduleStatus == "manual" { Text("Posting by hand").foregroundStyle(.secondary) }
250 if let destination = LinkedInDestination(fields: draft.fields["linkedinDestination"] as? [String: Any]) {
251 Text(destination.name).foregroundStyle(.secondary)
252 }
253 if let error = draft.schedule["error"] as? String, !error.isEmpty {
254 Text(error).foregroundStyle(.secondary)
255 }
256 if !draft["mediaError"].isEmpty {
257 Text(draft["mediaError"]).foregroundStyle(.secondary)
258 }
259 Spacer()
260 if generatingImages.contains(draft.id) { ProgressView().controlSize(.small) }
261 if let address = draft.schedule["url"] as? String, let url = URL(string: address),
262 url.scheme == "https", url.host != nil, url.user == nil, url.password == nil {
263 StudioExternalLink("Open post", destination: url)
264 }
265 if workspace.quoteComposerURL(for: draft) != nil {
266 Button {
267 workspace.perform { openURL(try workspace.prepareManualQuote(draft)) }
268 } label: {
269 StudioLinkOutLabel { Text("Open quote in X…") }
270 }
271 }
272 if !["posting", "posted"].contains(draft.scheduleStatus) {
273 Button("Edit draft") { open(draft) }
274 if draft.offersPostNow {
275 Button("Post now…", systemImage: "paperplane") {
276 reviewPublication(draft, nil) { _ in tab = .history }
277 }
278 }
279 StudioFilterMenu(title: "Post actions", value: "Actions") {
280 if !draft.body.isEmpty {
281 Button("Record as posted…") { manuallyPosted = draft }
282 if workspace.writingToolsAvailable, draft.scheduleStatus != "skipped" {
283 Button("Rewrite with notes…") {
284 revise(draft) { updated in
285 if ScheduleListing.section(for: updated) == .ready { tab = .ready }
286 }
287 }
288 }
289 }
290 if ["ready", "removed", "failed", "manual", "queued", "due"].contains(draft.scheduleStatus) {
291 Button("Skip post") { workspace.perform { try update(draft, status: "skipped") } }
292 }
293 if ["x", "instagram"].contains(draft["platform"]),
294 !draft["mediaPlan"].isEmpty || !draft["mediaError"].isEmpty ||
295 draft["platform"] == "instagram" && draft.fields["image"] == nil {
296 Button(draft["mediaError"].isEmpty ? "Generate image" : "Retry image") {
297 Task { await generateImage(draft) }
298 }
299 .disabled(generatingImages.contains(draft.id))
300 }
301 if workspace.records.contains(where: { $0.id == draft["ideaId"] && $0["status"] == "picked" }) {
302 Button("Reopen source idea…") {
303 workspace.perform { returningIdea = try workspace.reviewIdeaReturn(for: draft) }
304 }
305 }
306 }
307 }
308 if draft.fields["manualQuote"] as? Bool != true,
309 ["queued", "due", "skipped", "manual"].contains(draft.scheduleStatus) {
310 Button("Move to ready") {
311 workspace.perform { try update(draft, status: "ready") }
312 }
313 }
314 if ["ready", "queued", "failed", "removed"].contains(draft.scheduleStatus),
315 draft.fields["manualQuote"] as? Bool != true {
316 Button("Choose a time…") {
317 chooseTime(draft) { tab = .scheduled }
318 }
319 }
320 }
321 }
322 }
323
324 private func publishedCard(_ post: CompanionPublication) -> some View {
325 VStack(alignment: .leading, spacing: 8) {
326 StudioPlatformLabel(name: post.channel, title: post.channelName).font(.callout.weight(.semibold))
327 Text(post.title).font(.headline)
328 Text("\(post.project) · \(post.publishedAt.formatted(date: .abbreviated, time: .shortened))")
329 .font(.callout).foregroundStyle(palette.muted)
330 if post.incomplete { Text("Partially published").font(.caption).foregroundStyle(palette.muted) }
331 ForEach(Array(post.links.enumerated()), id: \.offset) { index, link in
332 StudioExternalLink(index == 0 ? "Open on \(post.channelName)" : "Open follow-up \(index)", destination: link)
333 }
334 if post.links.isEmpty {
335 if let draft = workspace.records.first(where: { $0.id == post.id && $0.kind == "draft" && $0.scheduleStatus == "posted" }) {
336 Button("Add post link…", systemImage: "link") {
337 publishedLink = ""
338 editingPublishedLink = draft
339 }
340 } else {
341 Text("No post link saved").font(.caption).foregroundStyle(palette.muted)
342 }
343 }
344 }
345 .frame(maxWidth: .infinity, alignment: .leading)
346 .padding(14)
347 .studioSurface()
348 }
349
350 private var emptyMessage: String {
351 switch tab {
352 case .scheduled: "Nothing scheduled"
353 case .ready: "Nothing ready to schedule"
354 case .history: "No published posts"
355 }
356 }
357
358 private func projectName(for record: WorkspaceRecord) -> String {
359 workspace.projects.first { $0.id == record.projectID }?.title ?? "Inkspring"
360 }
361
362 private func scheduledDay(_ record: WorkspaceRecord) -> Date? {
363 ScheduleListing.date(for: record, in: .scheduled).map { Calendar.current.startOfDay(for: $0) }
364 }
365
366 private func newsletterCard(_ item: WorkspaceRecord) -> some View {
367 let state = item["state"]
368 let editable = ["draft", "synced"].contains(state)
369 let reschedulable = state == "scheduled"
370 return VStack(alignment: .leading, spacing: 8) {
371 RecordCard(record: item)
372 HStack {
373 Text(projectName(for: item)).foregroundStyle(.secondary)
374 Text(newsletterStatus(item)).foregroundStyle(.secondary)
375 if tab != .ready, let date = ScheduleListing.date(for: item, in: tab) {
376 Text(date.formatted(date: .abbreviated, time: .shortened))
377 }
378 Spacer()
379 Button(editable ? "Edit draft" : "View newsletter") { open(item) }
380 StudioFilterMenu(title: "Newsletter actions", value: "Actions") {
381 if editable {
382 Button("Save to Substack") {
383 runNewsletterAction { try await Substack(workspace: workspace).sync(item.id) }
384 }
385 .disabled(Substack(workspace: workspace).selected == nil || item.body.isEmpty)
386 Button("Review & publish…") { beginNewsletterSend(item, scheduling: false) }
387 }
388 if reschedulable {
389 Button("Cancel schedule…") { cancellingNewsletter = item }
390 }
391 if !item["remoteId"].isEmpty {
392 Button("Check status") {
393 runNewsletterAction { try await Substack(workspace: workspace).refresh(item.id) }
394 }
395 }
396 if state == "uncertain" {
397 Button("Confirm Substack check…") { checkingNewsletter = item }
398 }
399 if let url = Substack.editorURL(item) {
400 StudioExternalLink("Open in Substack", destination: url)
401 }
402 Button("Copy text", systemImage: "doc.on.doc") { copy(item.body) }
403 }
404 .disabled(workspace.substackBusy)
405 if editable || reschedulable {
406 Button("Choose a time…") { beginNewsletterSend(item, scheduling: true) }
407 .disabled(workspace.substackBusy)
408 }
409 }
410 }
411 }
412
413 private func beginNewsletterSend(_ item: WorkspaceRecord, scheduling: Bool) {
414 reviewNewsletter(item, scheduling) { saved in
415 if let section = ScheduleListing.section(for: saved) { tab = section }
416 }
417 }
418
419 private func runNewsletterAction(_ action: @escaping @MainActor () async throws -> WorkspaceRecord) {
420 Task {
421 do {
422 let updated = try await action()
423 if let section = ScheduleListing.section(for: updated) { tab = section }
424 } catch {
425 workspace.error = error.localizedDescription
426 }
427 }
428 }
429
430 private func newsletterStatus(_ item: WorkspaceRecord) -> String {
431 switch item["state"] {
432 case "scheduled": "Scheduled on Substack"
433 case "releasing": "Awaiting Substack confirmation"
434 case "uncertain": "Check Substack"
435 case "synced": "Saved to Substack"
436 case "published": "Published on Substack"
437 default: "Newsletter draft"
438 }
439 }
440
441 private func generateImage(_ draft: WorkspaceRecord) async {
442 guard generatingImages.insert(draft.id).inserted else { return }
443 defer { generatingImages.remove(draft.id) }
444 do {
445 _ = try await ContentStudio(workspace: workspace).makeImage(for: draft, prompt: draft["imagePrompt"])
446 } catch { workspace.error = error.localizedDescription }
447 }
448
449 private func update(_ draft: WorkspaceRecord, status: String) throws {
450 var draft = draft
451 var schedule = draft.schedule
452 if status == "posted" {
453 schedule["postedAt"] = WorkspaceRecord.timestamp
454 } else {
455 schedule["slotAt"] = ""
456 schedule["skippedAt"] = status == "skipped" ? WorkspaceRecord.timestamp : ""
457 }
458 schedule["status"] = status
459 schedule["error"] = ""
460 draft.fields["schedule"] = schedule
461 try workspace.save(draft)
462 }
463}
464
465struct ScheduleTimePage: View {
466 let draft: WorkspaceRecord
467 let workspace: Workspace
468 let close: () -> Void
469 let scheduled: () -> Void
470 let reviewPublication: (WorkspaceRecord, Date?, @escaping (WorkspaceRecord) -> Void) -> Void
471 @State private var postingTime = Date.now.addingTimeInterval(3600)
472 @State private var preferredHour = Date.now.addingTimeInterval(3600)
473 @State private var customTime = true
474 @State private var chosenMinute = -1
475 @State private var linkedInDestinations: [LinkedInDestination] = []
476 @State private var chosenDestination = ""
477 @State private var timeError: String?
478
479 private var selectedLinkedInDestination: LinkedInDestination? {
480 linkedInDestinations.first { $0.urn == chosenDestination }
481 }
482
483 private var offersCustomTime: Bool { ["x", "linkedin"].contains(draft["platform"]) }
484 private var usesCustomTime: Bool { offersCustomTime && customTime }
485
486 private var openHours: [Date] {
487 var proposed = draft
488 if let destination = selectedLinkedInDestination { proposed.fields["linkedinDestination"] = destination.fields }
489 return PostScheduling.proposedTimes(for: proposed, in: workspace.records, linkedInPersonalURN: linkedInDestinations.first?.urn,
490 window: workspace.postingWindow(for: draft["platform"]))
491 }
492
493 var body: some View {
494 StudioEditorPage(title: "Choose a posting time") {
495 Button("Cancel", role: .cancel, action: close).keyboardShortcut(.cancelAction)
496 Button(draft["platform"] == "tiktok" ? "Review TikTok post…" : "Schedule", action: schedule)
497 .modifier(PrimaryActionStyle())
498 .keyboardShortcut(.defaultAction)
499 .disabled(draft["platform"] == "linkedin" && selectedLinkedInDestination == nil)
500 } content: {
501 StudioScrollView {
502 VStack(alignment: .leading, spacing: 18) {
503 Text(draft.title).font(InkspringTypography.editorial(24))
504 if draft["platform"] == "linkedin" {
505 if linkedInDestinations.isEmpty {
506 Text("Connect LinkedIn in Connections before scheduling.").foregroundStyle(.secondary)
507 } else {
508 StudioLabeledChoice(title: "LinkedIn destination", selection: $chosenDestination,
509 options: linkedInDestinations.map(\.urn),
510 label: { urn in linkedInDestinations.first { $0.urn == urn }?.name ?? "Choose a destination" })
511 }
512 }
513 if offersCustomTime {
514 Picker("Scheduling", selection: $customTime) {
515 Text("Custom time").tag(true)
516 Text("Preferred hours").tag(false)
517 }
518 .pickerStyle(.segmented)
519 .fixedSize()
520 .onChange(of: customTime) { timeError = nil }
521 }
522 if !usesCustomTime {
523 let slots = openHours
524 if !slots.isEmpty {
525 StudioFilterMenu(title: "Open posting hours", value: "Open posting hours") {
526 ForEach(slots, id: \.self) { slot in
527 Button(slot.formatted(date: .abbreviated, time: .shortened)) { preferredHour = slot }
528 }
529 }
530 }
531 }
532 StudioDateTimePicker(selection: usesCustomTime ? $postingTime : $preferredHour, includesMinute: usesCustomTime)
533 if !usesCustomTime {
534 StudioLabeledChoice(title: "Posting minute", selection: $chosenMinute, options: Array(-1..<60),
535 label: { $0 < 0 ? "Choose automatically" : String(format: "%02d", $0) })
536 }
537 if offersCustomTime && workspace.settings["autoPost"] as? Bool != true {
538 Text("Automatic posting is off. Turn it on in Schedule to send this post at its scheduled time.")
539 .foregroundStyle(.secondary)
540 }
541 if draft.needsNativePostVideo {
542 Label("Inkspring sends this post once the platform has processed its video.", systemImage: "video")
543 .foregroundStyle(.secondary)
544 }
545 if offersCustomTime {
546 StudioExternalLink("Scheduling help", destination: URL(string: "https://inkspring.ai/help#schedule")!)
547 }
548 if let timeError { Text(timeError).foregroundStyle(.red) }
549 }
550 .frame(maxWidth: 920, alignment: .leading)
551 .studioPage()
552 }
553 }
554 .onChange(of: postingTime) { timeError = nil }
555 .onChange(of: preferredHour) { timeError = nil }
556 .onChange(of: chosenMinute) { timeError = nil }
557 .onChange(of: chosenDestination) { timeError = nil }
558 .onAppear {
559 if draft["platform"] == "linkedin" {
560 linkedInDestinations = (try? workspace.socialAccounts.savedLinkedInDestinations()) ?? []
561 }
562 let saved = LinkedInDestination(fields: draft.fields["linkedinDestination"] as? [String: Any])
563 chosenDestination = saved?.urn ?? linkedInDestinations.first?.urn ?? ""
564 let savedTime = (draft.schedule["slotAt"] as? String).flatMap(scheduleDate).flatMap { $0 > .now ? $0 : nil }
565 postingTime = savedTime ?? Date.now.addingTimeInterval(3600)
566 preferredHour = savedTime ?? openHours.first ?? postingTime
567 chosenMinute = workspace.postingMinute(for: draft["platform"])
568 }
569 }
570
571 private func schedule() {
572 do {
573 let slot = usesCustomTime ? PostScheduling.startOfMinute(postingTime)
574 : try workspace.preferredPostingDate(for: draft["platform"], hour: preferredHour, minute: chosenMinute)
575 if draft["platform"] == "tiktok" {
576 reviewPublication(draft, slot) { _ in scheduled() }
577 } else {
578 let result = try workspace.scheduleDraft(draft, at: slot, linkedin: selectedLinkedInDestination, customTime: usesCustomTime)
579 workspace.showPostResult(result)
580 scheduled()
581 close()
582 }
583 } catch { timeError = error.localizedDescription }
584 }
585}
586
587struct ScheduledDraftRevision: View {
588 @State var draft: WorkspaceRecord
589 let workspace: Workspace
590 let saved: (WorkspaceRecord) -> Void
591 let close: () -> Void
592 @State private var notes = ""
593 @State private var request: String?
594 @State private var error: String?
595
596 var body: some View {
597 StudioEditorPage(title: "Rewrite with notes") {
598 Button("Done", action: close).keyboardShortcut(.cancelAction)
599 .disabled(request != nil)
600 if request != nil {
601 ProgressView("Rewriting…").controlSize(.small)
602 } else {
603 Button("Rewrite draft") {
604 error = nil
605 request = notes.trimmingCharacters(in: .whitespacesAndNewlines)
606 }
607 .modifier(PrimaryActionStyle())
608 .keyboardShortcut(.defaultAction)
609 .disabled(notes.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || notes.utf16.count > 4_000)
610 }
611 } content: {
612 StudioScrollView {
613 VStack(alignment: .leading, spacing: 16) {
614 Text(draft.title).font(.headline)
615 Text(draft.body).textSelection(.enabled)
616 .frame(maxWidth: .infinity, alignment: .leading)
617 .padding(16)
618 .studioSurface()
619 if ["queued", "due"].contains(draft.scheduleStatus) {
620 Text("Changing the wording moves this post to Ready to schedule.").foregroundStyle(.secondary)
621 }
622 if !draft["notesReply"].isEmpty {
623 Text(draft["notesReply"]).foregroundStyle(.secondary)
624 }
625 DraftBodyField(text: $notes, label: "Revision notes", minHeight: 140)
626 .disabled(request != nil)
627 if let error { Text(error).foregroundStyle(.red) }
628 if !draft["previousContent"].isEmpty {
629 Button("Restore earlier wording") {
630 do {
631 draft = try ContentStudio(workspace: workspace).undoRewrite(draft)
632 error = nil
633 saved(draft)
634 } catch {
635 self.error = error.localizedDescription
636 }
637 }
638 .disabled(request != nil)
639 }
640 }
641 .frame(maxWidth: 920, alignment: .leading)
642 .studioPage()
643 }
644 }
645 .task(id: request) {
646 guard let request else { return }
647 defer { self.request = nil }
648 do {
649 draft = try await ContentStudio(workspace: workspace).rewrite(draft, notes: request)
650 notes = ""
651 saved(draft)
652 } catch is CancellationError {
653 return
654 } catch {
655 self.error = error.localizedDescription
656 }
657 }
658 }
659}
660
661private struct XPostingHours: View {
662 let records: [WorkspaceRecord]
663
664 var body: some View {
665 TimelineView(.periodic(from: .now, by: 60)) { context in
666 let calendar = Calendar.current
667 VStack(alignment: .leading, spacing: 16) {
668 HStack(alignment: .firstTextBaseline, spacing: 12) {
669 Text("X posting hours").font(InkspringTypography.editorial(21))
670 .accessibilityAddTraits(.isHeader)
671 Spacer()
672 Text("All projects").font(.caption).foregroundStyle(.secondary)
673 }
674 StudioRule()
675 ViewThatFits(in: .horizontal) {
676 HStack(alignment: .top, spacing: 20) {
677 days(from: context.date, calendar: calendar, axis: .vertical)
678 }
679 VStack(alignment: .leading, spacing: 16) {
680 days(from: context.date, calendar: calendar, axis: .horizontal)
681 }
682 }
683 }
684 .padding(18)
685 .frame(maxWidth: .infinity, alignment: .leading)
686 .studioSurface()
687 }
688 }
689
690 @ViewBuilder private func days(from now: Date, calendar: Calendar, axis: Axis) -> some View {
691 day("Today", date: now, now: now, calendar: calendar)
692 if let tomorrow = calendar.date(byAdding: .day, value: 1, to: now) {
693 StudioRule(axis: axis)
694 .frame(height: axis == .vertical ? 177 : nil)
695 day("Tomorrow", date: tomorrow, now: now, calendar: calendar)
696 }
697 }
698
699 private func day(_ title: String, date: Date, now: Date, calendar: Calendar) -> some View {
700 VStack(alignment: .leading, spacing: 8) {
701 HStack {
702 Text(title).font(.subheadline.weight(.semibold))
703 Spacer()
704 Text(date.formatted(.dateTime.month(.abbreviated).day())).font(.caption).foregroundStyle(.secondary)
705 }
706 ForEach(PostScheduling.xPostingHours(on: date, in: records, calendar: calendar)) { hour in
707 HStack(alignment: .firstTextBaseline, spacing: 8) {
708 Text(hour.start, format: .dateTime.hour())
709 .monospacedDigit().frame(minWidth: 52, alignment: .leading)
710 if let post = hour.post {
711 Label(post.body.isEmpty ? post.title : post.body,
712 systemImage: post.scheduleStatus == "posted" ? "checkmark.circle" : "clock")
713 .lineLimit(1)
714 } else {
715 Text(hour.end <= now ? "Nothing posted" : "Open").foregroundStyle(.secondary)
716 }
717 Spacer(minLength: 0)
718 }
719 .font(.callout)
720 .padding(.vertical, 3)
721 .accessibilityElement(children: .combine)
722 }
723 }
724 .frame(minWidth: 200, maxWidth: .infinity, alignment: .leading)
725 }
726}
727
728func scheduleDate(_ value: String) -> Date? {
729 (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(value))
730 ?? (try? Date.ISO8601FormatStyle().parse(value))
731}