Branchwell

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

Raw 98.2 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import AppKit
2import AVFoundation
3import ImageIO
4import QuickLookThumbnailing
5import SwiftUI
6import UniformTypeIdentifiers
7import InkspringSchedule
8
9struct StudioEditorPage<Content: View, Actions: View>: View {
10 let title: String
11 @ViewBuilder let actions: () -> Actions
12 @ViewBuilder let content: () -> Content
13
14 var body: some View {
15 VStack(spacing: 0) {
16 HStack(spacing: 12) {
17 PageHeading(title: title, titleSize: 30)
18 Spacer()
19 actions()
20 }
21 .padding(.horizontal, 36)
22 .padding(.vertical, 20)
23 StudioRule()
24 content()
25 .frame(maxWidth: .infinity, maxHeight: .infinity)
26 }
27 }
28}
29
30struct PostInlineEditor: View {
31 @Environment(\.studioPalette) private var palette
32 let record: WorkspaceRecord
33 let workspace: Workspace
34 let back: () -> Void
35 let saved: () -> Void
36 let onDirty: (Bool) -> Void
37 let openArticle: (WorkspaceRecord, WorkspaceRecord) -> Void
38 @State private var title = ""
39 @State private var markdown = ""
40 @State private var format = ""
41 @State private var xArticleID = ""
42 @State private var showingHistory = false
43 @State private var message: String?
44 @State private var writingAssistantOpen = false
45 @State private var baseline: WorkspaceRecord?
46 @State private var attachingVideo = false
47
48 private var current: WorkspaceRecord { workspace.records.first { $0.id == record.id } ?? record }
49 private var dirty: Bool {
50 let base = baseline ?? record
51 return title != base.title || markdown != base.body || format != base["format"]
52 || xArticleID != base["xArticleID"]
53 }
54
55 var body: some View {
56 if showingHistory {
57 ContentRevisionHistoryPage(record: record, workspace: workspace, back: { showingHistory = false }) { _ in saved() }
58 } else {
59 editorContent
60 }
61 }
62
63 private var editorContent: some View {
64 VStack(alignment: .leading, spacing: 14) {
65 HStack {
66 Button("Back", systemImage: "chevron.left", action: back)
67 .help("Back to the post")
68 .keyboardShortcut(.cancelAction)
69 if let reference = record.referenceID {
70 StudioCopyReference(reference: reference)
71 }
72 Spacer()
73 if workspace.writingToolsAvailable {
74 Button("Ask AI", systemImage: "bubble.left.and.text.bubble.right") { writingAssistantOpen.toggle() }
75 .disabled(!current.acceptsRevisionComments).accessibilityIdentifier("writing.tools")
76 }
77 Button("Revision history", systemImage: "clock.arrow.circlepath") { showingHistory = true }
78 .disabled(dirty)
79 Button("Save", action: save)
80 .modifier(PrimaryActionStyle())
81 .keyboardShortcut("s")
82 .disabled(!dirty)
83 }
84 if writingAssistantOpen, workspace.writingToolsAvailable {
85 ScrollView {
86 StudioWritingAssistant(agent: StudioWritingConnection(settings: workspace.settings) == .agent ? StudioChatAgent.writingAgent(settings: workspace.settings).rawValue : WritingProviders(settings: workspace.settings).writingProvider.rawValue,
87 requests: current.revisionRequests.map(StudioWritingRequest.init),
88 reply: current["notesReply"], error: current["writingRequestError"].isEmpty ? nil : current["writingRequestError"]) { prompt in
89 if dirty {
90 try workspace.updatePostText(baseline ?? record, title: title, text: markdown, format: format,
91 xArticleID: xArticleID)
92 baseline = current
93 }
94 try workspace.addComment(to: current, text: prompt, revisionRequestID: UUID().uuidString.lowercased())
95 Task { await workspace.runDraftRevisionComments() }
96 }
97 .padding(14).studioSurface(fill: palette.well)
98 }.frame(maxHeight: 240)
99 }
100 DraftTitleField(title: $title)
101 articlePicker
102 if ["x", "linkedin", "instagram"].contains(current["platform"]), !["posting", "posted", "uncertain"].contains(current.scheduleStatus) {
103 videoAttachment
104 }
105 if workspace.agentConnected {
106 StudioProofreadAction(document: .init(title: title, body: markdown),
107 check: { try await ContentStudio.proofread($0, workspace: workspace) }) {
108 title = $0.title
109 markdown = $0.body
110 }
111 }
112 DraftPostText(workspace: workspace, record: record, text: $markdown, format: $format, label: "Markdown", minHeight: 100)
113 .frame(maxHeight: .infinity)
114 if ["queued", "due"].contains(record.scheduleStatus) {
115 Text("Saving changes moves this post to Ready to schedule.").foregroundStyle(.secondary)
116 }
117 if let message { Text(message).foregroundStyle(palette.danger) }
118 }
119 .padding(.horizontal, 24)
120 .padding(.vertical, 16)
121 .disabled(attachingVideo)
122 .onAppear { loadCurrent() }
123 .onChange(of: current["updatedAt"]) {
124 guard !dirty else { return }
125 loadCurrent()
126 }
127 .onChange(of: dirty) { _, changed in onDirty(changed) }
128 }
129
130 private var videoAttachment: some View {
131 HStack(spacing: 10) {
132 Button(current.needsNativePostVideo ? "Replace video…" : "Attach video…", systemImage: "video") {
133 guard let file = workspace.chooseMedia([.mpeg4Movie]), saveChanges() else { return }
134 let expected = current
135 attachingVideo = true
136 message = nil
137 Task {
138 defer { attachingVideo = false }
139 do {
140 let video = try await workspace.attachVideo(file)
141 try workspace.withChanges {
142 var post = current
143 guard post["updatedAt"] == expected["updatedAt"] else {
144 throw WorkspaceError("The post changed while attaching the video. Reopen the post and try again.")
145 }
146 post.setDraftMedia(video, as: .video)
147 if post["platform"] == "instagram" { post["format"] = "video" }
148 else if post["format"] == "image" { post["format"] = "post" }
149 _ = try PostVideo.forDraft(post, in: workspace.records)
150 try workspace.save(post)
151 }
152 loadCurrent()
153 } catch { message = error.localizedDescription }
154 }
155 }
156 if attachingVideo {
157 ProgressView().controlSize(.small)
158 } else if let video = current.fields["video"] as? [String: Any], let name = video["name"] as? String {
159 Text(name).font(.caption).foregroundStyle(.secondary).lineLimit(1)
160 }
161 }
162 }
163
164 @ViewBuilder private var articlePicker: some View {
165 if record["platform"] == "x", !["posting", "posted"].contains(current.scheduleStatus) {
166 let hasText = !markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
167 let create: (() -> Void)? = hasText && format != "reply" ? { createLinkedArticle() } : nil
168 PostArticlePicker(workspace: workspace, projectID: record.projectID, articleID: $xArticleID,
169 openArticle: openAttachedArticle, createArticle: create,
170 xReplyArticles: workspace.xReplyArticles(for: current, body: markdown))
171 }
172 }
173
174 private func loadCurrent() {
175 title = current.title
176 markdown = current.body
177 format = current["format"]
178 xArticleID = current["xArticleID"]
179 baseline = current
180 }
181
182 private func save() {
183 if saveChanges() { saved() }
184 }
185
186 private func saveChanges() -> Bool {
187 guard dirty else { return true }
188 do {
189 try workspace.updatePostText(baseline ?? record, title: title, text: markdown, format: format,
190 xArticleID: xArticleID)
191 loadCurrent()
192 onDirty(false)
193 return true
194 } catch {
195 message = error.localizedDescription
196 return false
197 }
198 }
199
200 private func openAttachedArticle(_ article: WorkspaceRecord) {
201 guard saveChanges() else { return }
202 openArticle(article, current)
203 }
204
205 private func createLinkedArticle() {
206 guard saveChanges() else { return }
207 workspace.perform {
208 let article = try workspace.linkedArticleDraft(from: current)
209 loadCurrent()
210 openArticle(article, current)
211 }
212 }
213}
214
215struct RecordEditor: View {
216 @Environment(\.studioPalette) private var palette
217 @Environment(\.scenePhase) private var scenePhase
218 @FocusState private var newsletterField: NewsletterField?
219 @State var record: WorkspaceRecord
220 let workspace: Workspace
221 let saved: (WorkspaceRecord) -> Void
222 let closeRecord: () -> Void
223 let closeNewsletter: () -> Void
224 let newsletterDirtyChanged: (Bool) -> Void
225 let newsletterSaveBeforeLeaving: ((() -> Bool)?) -> Void
226 let reviewNewsletter: (WorkspaceRecord, Bool, @escaping (WorkspaceRecord) -> Void) -> Void
227 private let original: WorkspaceRecord
228 @State private var newsletterBase: WorkspaceRecord
229 @State private var newsletterSaveError: String?
230 @State private var message: String?
231 @State private var showsOutline = false
232 @State private var newsletterMode = "Source"
233 @State private var newsletterFindRequest = 0
234 @State private var writingAssistantOpen = false
235 @State private var newsletterInspectorOpen = false
236 @State private var showingHistory = false
237 @State private var newsletterBrief = ""
238 @State private var newsletterAssistantOpen = false
239 @State private var newsletterIdeaOutline = false
240 @State private var newsletterSources: Set<String> = []
241 @State private var newsletterWriting: Task<Void, Never>?
242 @State private var showsCoverGenerator = false
243 @State private var coverPrompt = ""
244 @State private var ideaSuggestion: PostIdeaText?
245 @State private var shapingIdea = false
246
247 private enum NewsletterField: Hashable { case title, subtitle }
248
249 init(record: WorkspaceRecord, workspace: Workspace, newsletterIdea: WorkspaceRecord? = nil,
250 closeRecord: @escaping () -> Void = {},
251 closeNewsletter: @escaping () -> Void = {},
252 newsletterDirtyChanged: @escaping (Bool) -> Void = { _ in },
253 newsletterSaveBeforeLeaving: @escaping ((() -> Bool)?) -> Void = { _ in },
254 reviewNewsletter: @escaping (WorkspaceRecord, Bool, @escaping (WorkspaceRecord) -> Void) -> Void = { _, _, _ in },
255 saved: @escaping (WorkspaceRecord) -> Void) {
256 _record = State(initialValue: record)
257 _newsletterBase = State(initialValue: record)
258 original = record
259 if record.kind == "newsletter", !["draft", "synced"].contains(record["state"]) {
260 _newsletterMode = State(initialValue: "Preview")
261 }
262 self.workspace = workspace
263 self.saved = saved
264 self.closeRecord = closeRecord
265 self.closeNewsletter = closeNewsletter
266 self.newsletterDirtyChanged = newsletterDirtyChanged
267 self.newsletterSaveBeforeLeaving = newsletterSaveBeforeLeaving
268 self.reviewNewsletter = reviewNewsletter
269 if let idea = newsletterIdea {
270 let direction = """
271 Develop this post idea into a newsletter concept. Include the angle, why it matters, and a short outline in Markdown.
272 \(PostIdeaWriting.draftingInstructions)
273
274 \(idea.title)
275 \(idea.body)
276 """
277 _newsletterBrief = State(initialValue: String(decoding: direction.utf16.prefix(10_000), as: UTF16.self))
278 _newsletterAssistantOpen = State(initialValue: true)
279 _newsletterInspectorOpen = State(initialValue: true)
280 _newsletterIdeaOutline = State(initialValue: true)
281 }
282 }
283
284 private var latestNewsletter: WorkspaceRecord? {
285 workspace.records.first { $0.isLongForm && $0.id == record.id }
286 }
287
288 private var canEditNewsletter: Bool { ["draft", "synced"].contains((latestNewsletter ?? record)["state"]) }
289
290 private var newsletterHasEdits: Bool {
291 return ["title", "subtitle", "body", "audience"].contains { record[$0] != newsletterBase[$0] } ||
292 Substack.emails(record) != Substack.emails(newsletterBase) ||
293 (record.fields["coverImage"] as? NSDictionary) != (newsletterBase.fields["coverImage"] as? NSDictionary)
294 }
295
296 private var newsletterNeedsSave: Bool {
297 if latestNewsletter != nil { return newsletterHasEdits }
298 return ["title", "subtitle", "body"].contains { !record[$0].isEmpty }
299 || record.fields["coverImage"] != nil
300 }
301
302 private var newsletterAutosaveValues: [String] {
303 [record["title"], record["subtitle"], record["body"]]
304 }
305
306 var body: some View {
307 if showsOutline, let latestNewsletter {
308 WorkspaceOutline(record: latestNewsletter, workspace: workspace) { showsOutline = false }
309 } else if showingHistory, let latestNewsletter {
310 ContentRevisionHistoryPage(record: latestNewsletter, workspace: workspace, back: { showingHistory = false }) { restored in
311 acceptNewsletter(restored)
312 saved(restored)
313 showingHistory = false
314 }
315 } else if record.isLongForm {
316 newsletterEditor
317 .onChange(of: newsletterNeedsSave, initial: true) { _, dirty in
318 newsletterDirtyChanged(dirty)
319 }
320 .onChange(of: latestNewsletter?["updatedAt"]) {
321 if let latestNewsletter, !newsletterHasEdits { acceptNewsletter(latestNewsletter) }
322 }
323 .onAppear { newsletterSaveBeforeLeaving(saveNewsletter) }
324 .task(id: newsletterAutosaveValues) {
325 guard newsletterNeedsSave else { return }
326 do { try await Task.sleep(for: .milliseconds(750)) }
327 catch { return }
328 _ = saveNewsletter()
329 }
330 .onChange(of: newsletterField) { previous, _ in
331 if previous != nil { _ = saveNewsletter() }
332 }
333 .onChange(of: newsletterMode) { _, mode in
334 if mode == "Preview" { _ = saveNewsletter() }
335 }
336 .onChange(of: scenePhase) { _, phase in
337 if phase != .active { _ = saveNewsletter() }
338 }
339 .onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in
340 _ = saveNewsletter()
341 }
342 .onDisappear {
343 newsletterWriting?.cancel()
344 _ = saveNewsletter()
345 newsletterSaveBeforeLeaving(nil)
346 }
347 } else {
348 recordPage
349 }
350 }
351
352 private var recordPage: some View {
353 StudioEditorPage(title: heading) {
354 Button("Cancel", role: .cancel, action: closeRecord)
355 .keyboardShortcut(.cancelAction)
356 Button(record.kind == "idea" ? "Save idea" : "Save", action: saveRecord)
357 .modifier(PrimaryActionStyle())
358 .keyboardShortcut("s")
359 .disabled(!hasRecordEdits || record.kind == "idea" && !validIdea)
360 } content: {
361 StudioScrollView {
362 VStack(alignment: .leading, spacing: 14) {
363 switch record.kind {
364 case "project":
365 field("Project name", "name")
366 field("Description", "description", multiline: true)
367 field("Audience", "audience", multiline: true)
368 field("Writing voice", "voice", multiline: true)
369 field("Research focus", "researchFocus", multiline: true)
370 HStack {
371 ColorPicker("Project color", selection: projectColor, supportsOpacity: false)
372 StudioChoicePicker(title: "Icon", selection: value("icon"),
373 options: ["dot", "folder", "studio", "ink", "book", "video", "idea", "flask",
374 "code", "globe", "mic", "waveform"], label: { $0.capitalized })
375 }
376 case "source":
377 field("Title", "title")
378 field("Source URL", "url")
379 field("Author", "author")
380 field("Notes", "text", multiline: true, height: 160)
381 case "idea":
382 field("Working title", "topic")
383 field("Angle or notes", "text", multiline: true, height: 235)
384 if original["topic"].isEmpty { ideaWritingHelp }
385 field("Media plan", "mediaPlan")
386 field("Notes", "notes", multiline: true)
387 Toggle("Include a plan", isOn: Binding(get: { record.fields["planMarkdown"] != nil }, set: {
388 record.fields["planMarkdown"] = $0 ? ContentPlan.starter(record.title) : nil
389 }))
390 if record.fields["planMarkdown"] != nil {
391 ContentPlanSection(markdown: record["planMarkdown"], reference: record.referenceID ?? record.id,
392 context: record.title, recoveryID: record.id) { text, base in
393 guard record["planMarkdown"] == base else { throw ContentPlanError.conflict }
394 record["planMarkdown"] = text
395 }
396 }
397 StudioLabeledChoice(title: "Status", selection: value("status"),
398 options: ["draft", "picked", "skipped"],
399 label: { $0 == "draft" ? "Open" : $0.capitalized })
400 default:
401 EmptyView()
402 }
403 if let message { Text(message).foregroundStyle(palette.danger) }
404 }
405 .frame(maxWidth: 920, alignment: .leading)
406 .padding(.horizontal, 36)
407 .padding(.vertical, 24)
408 .frame(maxWidth: .infinity)
409 }
410 }
411 .onChange(of: ideaText) { ideaSuggestion = nil }
412 }
413
414 private var hasRecordEdits: Bool {
415 (original.fields as NSDictionary) != (record.fields as NSDictionary)
416 }
417
418 private var validIdea: Bool {
419 !ideaText.title.isEmpty && !ideaText.body.isEmpty
420 }
421
422 private var ideaText: PostIdeaText {
423 PostIdeaText(title: record["topic"], body: record["text"])
424 }
425
426 private var ideaWritingHelp: some View {
427 VStack(alignment: .leading, spacing: 10) {
428 Button("Shape with Claude", systemImage: "sparkles") { Task { await shapeIdea() } }
429 .disabled(shapingIdea || !workspace.agentAccessEnabled || StudioChatAgent.claude.executable == nil
430 || ideaText.isEmpty)
431 if shapingIdea { ProgressView("Claude is shaping the idea…").controlSize(.small) }
432 if let ideaSuggestion {
433 VStack(alignment: .leading, spacing: 8) {
434 Text(ideaSuggestion.title).font(.headline)
435 Text(ideaSuggestion.body).textSelection(.enabled)
436 HStack {
437 Button("Use this idea") {
438 record["topic"] = ideaSuggestion.title
439 record["text"] = ideaSuggestion.body
440 self.ideaSuggestion = nil
441 }.modifier(PrimaryActionStyle())
442 Button("Dismiss") { self.ideaSuggestion = nil }
443 }
444 }.padding(12).studioSurface()
445 }
446 }
447 }
448
449 private func shapeIdea() async {
450 let source = ideaText
451 guard !shapingIdea, !source.isEmpty else { return }
452 ideaSuggestion = nil
453 shapingIdea = true
454 message = nil
455 defer { shapingIdea = false }
456 do {
457 let model = StudioChatAgent.claude.writingModel(workspace: workspace, providers: WritingProviders(settings: workspace.settings))
458 let result = try await model.object("""
459 \(PostIdeaWriting.shapingInstructions)
460 Return one rewrite of the idea.
461 Return an object with strings title (up to 140 characters) and body (up to 2,000 characters).
462 """, ["title": source.title, "notes": source.body])
463 guard ideaText == source else { return }
464 let suggestion = PostIdeaText(title: result["title"] as? String ?? "", body: result["body"] as? String ?? "")
465 guard suggestion.canSaveOnMobile else {
466 throw WorkspaceError("Claude didn’t return a usable idea. Try again or keep editing your notes.")
467 }
468 ideaSuggestion = suggestion
469 } catch {
470 message = error.localizedDescription
471 }
472 }
473
474 private func saveRecord() {
475 do {
476 if record.kind == "source" && record["origin"].isEmpty { record["origin"] = "Imported" }
477 let isNewIdea = record.kind == "idea"
478 && !record.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
479 && !workspace.records.contains { $0.id == record.id }
480 let result = try workspace.save(record)
481 if isNewIdea { InkspringReview.recordActivity() }
482 saved(result)
483 } catch {
484 message = error.localizedDescription
485 }
486 }
487
488 private var newsletterUnavailable: Bool { (record.kind == "newsletter" && workspace.substackBusy) || newsletterWriting != nil }
489
490 private var newsletterEditor: some View {
491 VStack(spacing: 0) {
492 HStack(spacing: 14) {
493 Button("Back", systemImage: "chevron.left", action: closeNewsletter)
494 .help("Return to the previous view")
495 .keyboardShortcut(.cancelAction)
496 if let reference = latestNewsletter?.referenceID {
497 StudioCopyReference(reference: reference)
498 }
499 Spacer()
500 StudioSegmentedControl(selection: $newsletterMode, options: ["Source", "Preview"], label: Text.init)
501 .accessibilityLabel("Document view")
502 Spacer()
503 if workspace.writingToolsAvailable {
504 Button("Ask AI", systemImage: "bubble.left.and.text.bubble.right") {
505 writingAssistantOpen.toggle()
506 if writingAssistantOpen { newsletterInspectorOpen = false }
507 }
508 .buttonStyle(StudioIconButtonStyle()).help("Ask AI")
509 .disabled(!canEditNewsletter).accessibilityIdentifier("writing.tools")
510 }
511 Button("Find", systemImage: "magnifyingglass") { newsletterMode = "Source"; newsletterFindRequest += 1 }
512 .buttonStyle(StudioIconButtonStyle()).help("Find in document")
513 .keyboardShortcut("f", modifiers: .command).accessibilityIdentifier("editor.find")
514 Button("Revision history", systemImage: "clock.arrow.circlepath") {
515 if saveNewsletter() { showingHistory = true }
516 }
517 .buttonStyle(StudioIconButtonStyle()).help("Revision history")
518 .accessibilityIdentifier("history.open")
519 if record.kind == "newsletter" {
520 let inspectorTitle = newsletterInspectorOpen ? "Hide newsletter settings" : "Show newsletter settings"
521 Button(inspectorTitle, systemImage: "sidebar.right") {
522 newsletterInspectorOpen.toggle()
523 if newsletterInspectorOpen { writingAssistantOpen = false }
524 }
525 .buttonStyle(StudioIconButtonStyle())
526 .help(inspectorTitle)
527 }
528 Menu {
529 Button(latestNewsletter?["planMarkdown"].isEmpty == false ? "View outline" : "Add outline", action: openOutline)
530 } label: { Label("More", systemImage: "ellipsis.circle") }
531 .labelStyle(.iconOnly).help("More actions")
532 .disabled(latestNewsletter == nil && !newsletterNeedsSave)
533 VStack(alignment: .trailing, spacing: 3) {
534 if newsletterSaveError != nil {
535 Text("Unsaved changes")
536 } else if newsletterNeedsSave && canEditNewsletter {
537 Text("Saving…")
538 .accessibilityIdentifier("newsletter.autosaveStatus")
539 }
540 if let updatedAt = latestNewsletter.flatMap({ scheduleDate($0["updatedAt"]) }) {
541 Text("Last updated \(updatedAt.formatted(date: .abbreviated, time: .standard))")
542 .multilineTextAlignment(.trailing)
543 .lineLimit(2).frame(maxWidth: 180, alignment: .trailing)
544 .accessibilityIdentifier("newsletter.lastUpdated")
545 }
546 }
547 .font(.caption)
548 .foregroundStyle(palette.muted)
549 }
550 .fixedSize(horizontal: false, vertical: true)
551 .padding(18)
552 StudioRule()
553 if record.isXArticle {
554 XArticlePublishControls(workspace: workspace, article: latestNewsletter ?? record, save: saveNewsletter)
555 .fixedSize(horizontal: false, vertical: true).padding(.horizontal, 18).padding(.vertical, 10)
556 }
557 HStack(spacing: 0) {
558 newsletterCanvas
559 .frame(maxWidth: .infinity, maxHeight: .infinity)
560 if writingAssistantOpen, workspace.writingToolsAvailable {
561 StudioRule(axis: .vertical)
562 StudioScrollView {
563 StudioWritingAssistant(agent: StudioWritingConnection(settings: workspace.settings) == .agent ? StudioChatAgent.writingAgent(settings: workspace.settings).rawValue : WritingProviders(settings: workspace.settings).writingProvider.rawValue,
564 requests: (latestNewsletter ?? record).revisionRequests.map(StudioWritingRequest.init),
565 reply: (latestNewsletter ?? record)["notesReply"], error: (latestNewsletter ?? record)["writingRequestError"].isEmpty ? nil : (latestNewsletter ?? record)["writingRequestError"]) { prompt in
566 guard saveNewsletter(), let current = workspace.records.first(where: { $0.id == record.id }) else {
567 throw WorkspaceError("Save the current draft before asking for a change.")
568 }
569 try workspace.addComment(to: current, text: prompt, revisionRequestID: UUID().uuidString.lowercased())
570 Task { await workspace.runDraftRevisionComments() }
571 }
572 .padding(18).background(palette.sidebar)
573 }
574 .frame(width: 320)
575 .background(palette.sidebar)
576 }
577 if newsletterInspectorOpen && record.kind == "newsletter" {
578 StudioRule(axis: .vertical)
579 StudioScrollView {
580 newsletterSettings
581 .padding(.vertical, 18)
582 .padding(.leading, 16)
583 }
584 .frame(idealWidth: 320, maxWidth: 320)
585 .background(palette.sidebar)
586 }
587 }
588 if let detail = newsletterSaveError {
589 newsletterNotice("Couldn’t save changes", detail: detail) {
590 Button("Retry save") { _ = saveNewsletter() }
591 }
592 .accessibilityIdentifier("newsletter.saveNotice")
593 } else if let message {
594 newsletterNotice("Newsletter needs attention", detail: message) {
595 Button("Dismiss") { self.message = nil }
596 }
597 }
598 }
599 }
600
601 private func newsletterNotice<Actions: View>(_ title: String, detail: String,
602 @ViewBuilder actions: () -> Actions) -> some View {
603 HStack(alignment: .center, spacing: 10) {
604 Image(systemName: "exclamationmark.circle")
605 .foregroundStyle(palette.danger)
606 .accessibilityHidden(true)
607 VStack(alignment: .leading, spacing: 3) {
608 Text(title).font(.callout.weight(.semibold)).foregroundStyle(palette.text)
609 Text(detail).font(.caption).foregroundStyle(palette.muted)
610 .fixedSize(horizontal: false, vertical: true)
611 }
612 .frame(maxWidth: .infinity, alignment: .leading)
613 actions()
614 }
615 .padding(.vertical, 9)
616 .padding(.horizontal, 12)
617 .studioSurface(12, fill: palette.panel)
618 .padding(.horizontal, 18)
619 .padding(.vertical, 10)
620 }
621
622 @ViewBuilder private var newsletterCanvas: some View {
623 if newsletterMode == "Source" {
624 StudioScrollView {
625 VStack(alignment: .leading, spacing: 14) {
626 newsletterTextField("Title", key: "title", focus: .title)
627 newsletterTextField("Subtitle", key: "subtitle", focus: .subtitle)
628 DraftBodyField(text: value("body"), label: "Markdown", minHeight: 420,
629 onFocusLost: { _ = saveNewsletter() }, findRequest: newsletterFindRequest,
630 expandsWithDocument: true)
631 if workspace.agentConnected {
632 StudioProofreadAction(document: .init(title: record["title"], subtitle: record["subtitle"], body: record["body"]),
633 check: { try await ContentStudio.proofread($0, workspace: workspace) }) {
634 record["title"] = $0.title
635 record["subtitle"] = $0.subtitle
636 record["body"] = $0.body
637 }
638 }
639 outlineLink
640 }
641 .disabled(!canEditNewsletter || newsletterUnavailable)
642 .padding(22)
643 }
644 } else {
645 StudioScrollView {
646 NewsletterPreview(title: record["title"], subtitle: record["subtitle"],
647 markdown: record["body"], cover: workspace.mediaURL(record))
648 .frame(maxWidth: 880)
649 .frame(maxWidth: .infinity)
650 .padding(22)
651 outlineLink
652 .padding(.horizontal, 22)
653 }
654 }
655 }
656
657 private func openOutline() {
658 if saveNewsletter(), latestNewsletter != nil { showsOutline = true }
659 }
660
661 @ViewBuilder private var outlineLink: some View {
662 if latestNewsletter?["planMarkdown"].isEmpty == false {
663 Button("View outline", systemImage: "list.bullet.clipboard", action: openOutline)
664 .controlSize(.small)
665 }
666 }
667
668 private func newsletterTextField(_ label: String, key: String, focus: NewsletterField) -> some View {
669 VStack(alignment: .leading, spacing: 5) {
670 Text(label).font(.caption).foregroundStyle(.secondary)
671 TextField(label, text: value(key))
672 .studioInput()
673 .focused($newsletterField, equals: focus)
674 .onSubmit { _ = saveNewsletter() }
675 }
676 }
677
678 @discardableResult private func saveNewsletter() -> Bool {
679 guard newsletterNeedsSave else {
680 newsletterSaveError = nil
681 return true
682 }
683 guard canEditNewsletter else { return false }
684 do {
685 let isNewWriting = latestNewsletter == nil
686 && !record.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
687 acceptNewsletter(try workspace.saveNewsletterEditor(record, basedOn: newsletterBase))
688 if isNewWriting { InkspringReview.recordActivity() }
689 newsletterSaveError = nil
690 return true
691 } catch {
692 newsletterSaveError = error.localizedDescription
693 return false
694 }
695 }
696
697 private func acceptNewsletter(_ updated: WorkspaceRecord) {
698 record = updated
699 newsletterBase = updated
700 newsletterSaveError = nil
701 }
702
703 private var newsletterSettings: some View {
704 VStack(alignment: .leading, spacing: 14) {
705 if canEditNewsletter, workspace.writingToolsAvailable { newsletterAssistant }
706 VStack(alignment: .leading, spacing: 9) {
707 Button("Import Markdown…", action: importMarkdown).disabled(!canEditNewsletter || newsletterUnavailable)
708 Button("Export Markdown…") {
709 let subtitle = record["subtitle"].isEmpty ? "" : "*" + record["subtitle"] + "*\n\n"
710 saveMarkdown(title: record.title, contents: "# " + record.title + "\n\n" + subtitle + record["body"],
711 report: { message = $0 })
712 }
713 Button("Export HTML…", action: exportNewsletterHTML)
714 }
715 if newsletterMode == "Source" { AttachedMedia(url: workspace.mediaURL(record)) }
716 GroupBox("Cover image") {
717 VStack(alignment: .leading, spacing: 10) {
718 VStack(alignment: .leading, spacing: 8) {
719 Button("Generate cover…", systemImage: "sparkles") { showsCoverGenerator.toggle() }
720 Button("Attach cover image…", systemImage: "photo") {
721 if let url = workspace.chooseMedia([.png, .jpeg, .webP]) {
722 do {
723 record.fields["coverImage"] = try workspace.attachImage(url)
724 saveNewsletter()
725 }
726 catch { message = error.localizedDescription }
727 }
728 }
729 if record.fields["coverImage"] is [String: Any] {
730 Button("Remove cover") {
731 record.fields["coverImage"] = nil
732 saveNewsletter()
733 }
734 }
735 }
736 if showsCoverGenerator {
737 let imageProvider = WritingProviders(settings: workspace.settings).imageProvider
738 TextField("Describe the newsletter cover", text: $coverPrompt, axis: .vertical)
739 .lineLimit(2...4).studioInput()
740 if !imageProvider.isSaved {
741 Text("Add an image provider key in Settings → API keys to generate a cover.")
742 .font(.callout).foregroundStyle(.secondary)
743 }
744 Button("Generate cover", systemImage: "sparkles", action: generateNewsletterCover)
745 .disabled(!imageProvider.isSaved || coverPrompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
746 if newsletterWriting != nil {
747 ProgressView("Working…").controlSize(.small)
748 }
749 }
750 }
751 .frame(maxWidth: .infinity, alignment: .leading)
752 }
753 .disabled(!canEditNewsletter || newsletterUnavailable)
754 GroupBox("Audience and delivery") {
755 VStack(alignment: .leading, spacing: 12) {
756 StudioChoicePicker(title: "Audience", selection: Binding(get: { record["audience"] }, set: {
757 record["audience"] = $0
758 saveNewsletter()
759 }),
760 options: ["everyone", "only_paid", "founding"], label: Substack.audienceLabel)
761 Toggle("Email subscribers", isOn: Binding(
762 get: { Substack.emails(record) }, set: {
763 record.fields["sendEmail"] = $0
764 saveNewsletter()
765 }
766 ))
767 .tint(palette.accent)
768 }
769 .frame(maxWidth: .infinity, alignment: .leading)
770 }
771 .disabled(!canEditNewsletter || newsletterUnavailable)
772 if latestNewsletter != nil {
773 NewsletterSubstackControls(workspace: workspace, record: record, hasEdits: newsletterHasEdits,
774 updated: acceptNewsletter, report: { message = $0 },
775 reviewSend: { scheduling in reviewNewsletter(record, scheduling, acceptNewsletter) })
776 .disabled(newsletterWriting != nil)
777 if !canEditNewsletter {
778 Button("Make a new local copy", systemImage: "doc.on.doc") {
779 acceptNewsletter(NewsletterDocument.localCopy(of: record))
780 newsletterBrief = ""
781 newsletterSources.removeAll()
782 newsletterMode = "Source"
783 message = nil
784 }
785 .disabled(newsletterUnavailable)
786 }
787 }
788 }
789 }
790
791 private func generateNewsletterCover() {
792 guard canEditNewsletter, !newsletterUnavailable else { return }
793 let providers = WritingProviders(settings: workspace.settings)
794 let prompt = coverPrompt.trimmingCharacters(in: .whitespacesAndNewlines)
795 message = nil
796 newsletterWriting = Task {
797 defer { newsletterWriting = nil }
798 do {
799 let (bytes, fileExtension) = try await providers.image(prompt: prompt)
800 try Task.checkCancellation()
801 let file = try workspace.writeGeneratedImage(bytes, fileExtension: fileExtension)
802 record.fields["coverImage"] = ["file": file, "origin": providers.imageProvider.name, "prompt": prompt]
803 saveNewsletter()
804 showsCoverGenerator = false
805 } catch is CancellationError {
806 } catch { message = error.localizedDescription }
807 }
808 }
809
810 private var newsletterAssistant: some View {
811 DisclosureGroup("Write or refine with AI", isExpanded: $newsletterAssistantOpen) {
812 VStack(alignment: .leading, spacing: 10) {
813 TextField("Direction for the newsletter", text: $newsletterBrief, axis: .vertical)
814 .lineLimit(3...6)
815 .disabled(newsletterUnavailable)
816 let sources = workspace.records.filter { $0.kind == "source" && $0.projectID == record.projectID }
817 if !sources.isEmpty {
818 StudioFilterMenu(title: "References", value: "References (\(newsletterSources.count) selected)") {
819 ForEach(sources) { source in
820 Toggle(source.title, isOn: Binding(get: { newsletterSources.contains(source.id) }, set: { include in
821 if include && newsletterSources.count < 6 { newsletterSources.insert(source.id) }
822 else if !include { newsletterSources.remove(source.id) }
823 }))
824 .disabled(newsletterSources.count >= 6 && !newsletterSources.contains(source.id))
825 }
826 }
827 .disabled(newsletterUnavailable)
828 }
829 Text(StudioWritingConnection(settings: workspace.settings) == .agent
830 ? "Your selected agent receives the direction, draft, project details, writing profile, and selected references through Inkspring MCP."
831 : "Your direction, draft, project details, writing profile, and selected references go to your writing provider and use API credits.")
832 .font(.caption).foregroundStyle(.secondary)
833 HStack {
834 Button(newsletterIdeaOutline ? "Generate newsletter idea" : "Write with AI",
835 systemImage: "sparkles", action: writeNewsletter)
836 .disabled(newsletterUnavailable || newsletterBrief.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
837 newsletterBrief.utf16.count > 10_000)
838 if let newsletterWriting {
839 ProgressView().controlSize(.small)
840 Button("Stop") { newsletterWriting.cancel() }
841 }
842 }
843 }
844 .padding(.top, 6)
845 }
846 }
847
848 private func writeNewsletter() {
849 guard !newsletterUnavailable, saveNewsletter() else { return }
850 message = nil
851 let draft = record
852 let direction = newsletterBrief
853 let sources = newsletterSources
854 newsletterWriting = Task {
855 defer { newsletterWriting = nil }
856 do {
857 acceptNewsletter(try await ContentStudio(workspace: workspace)
858 .writeNewsletter(draft, brief: direction, sourceIDs: sources))
859 newsletterIdeaOutline = false
860 workspace.notice = "Newsletter draft saved for review."
861 } catch is CancellationError {
862 } catch { message = error.localizedDescription }
863 }
864 }
865
866 private func exportNewsletterHTML() {
867 do {
868 let document = try NewsletterDocument.parse(record["body"])
869 let html = NewsletterDocument.html(document, title: record.title, subtitle: record["subtitle"])
870 let panel = NSSavePanel()
871 panel.allowedContentTypes = [.html]
872 panel.nameFieldStringValue = record.title.replacingOccurrences(of: "/", with: "-") + ".html"
873 if panel.runModal() == .OK, let url = panel.url { try html.write(to: url, atomically: true, encoding: .utf8) }
874 } catch { message = error.localizedDescription }
875 }
876
877 private var heading: String {
878 switch record.kind {
879 case "project": record["name"].isEmpty ? "New project" : "Edit project"
880 case "source": original["title"].isEmpty ? "New research reference" : "Edit research reference"
881 case "idea": original["topic"].isEmpty ? "Draft a new idea" : "Edit idea"
882 default: "Edit"
883 }
884 }
885
886 private func value(_ key: String) -> Binding<String> {
887 Binding(get: { record[key] }, set: { record[key] = $0 })
888 }
889
890 private var projectColor: Binding<Color> {
891 Binding(get: { palette.project(record["color"]) }, set: { value in
892 guard let rgb = NSColor(value).usingColorSpace(.sRGB) else { return }
893 record["color"] = String(format: "#%02X%02X%02X", Int((rgb.redComponent * 255).rounded()),
894 Int((rgb.greenComponent * 255).rounded()), Int((rgb.blueComponent * 255).rounded()))
895 })
896 }
897
898 private func field(_ label: String, _ key: String, multiline: Bool = false, height: CGFloat = 60) -> some View {
899 VStack(alignment: .leading, spacing: 5) {
900 Text(label).font(.caption).foregroundStyle(.secondary)
901 if multiline {
902 TextEditor(text: value(key))
903 .font(.body)
904 .frame(minHeight: height)
905 .accessibilityLabel(label)
906 .scrollContentBackground(.hidden)
907 .padding(8)
908 .studioSurface(StudioRadius.control)
909 } else {
910 TextField(label, text: value(key)).studioInput()
911 }
912 }
913 }
914
915 private func importMarkdown() {
916 let panel = NSOpenPanel()
917 panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText, .plainText]
918 guard panel.runModal() == .OK, let url = panel.url else { return }
919 do {
920 let info = try url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey])
921 guard info.isRegularFile == true, let size = info.fileSize, size <= 800_000 else {
922 throw WorkspaceError("Choose a Markdown file under 800 KB.")
923 }
924 let content = try String(contentsOf: url, encoding: .utf8)
925 let draft = NewsletterDocument.importMarkdown(content, filename: url.deletingPathExtension().lastPathComponent)
926 record["title"] = draft.title
927 record["body"] = draft.body
928 } catch { message = error.localizedDescription }
929 }
930}
931
932struct ContentRevisionHistoryPage: View {
933 let record: WorkspaceRecord
934 let workspace: Workspace
935 let back: () -> Void
936 let restored: (WorkspaceRecord) -> Void
937 @Environment(\.studioPalette) private var palette
938 @State private var revisions: [ContentRevision] = []
939 @State private var selectedID: String?
940 @State private var message: String?
941
942 private var selected: ContentRevision? { revisions.first { $0.id == selectedID } }
943
944 var body: some View {
945 VStack(alignment: .leading, spacing: 16) {
946 HStack {
947 Button("Back", systemImage: "chevron.left", action: back)
948 Text("Revision history").font(.title2.bold())
949 Spacer()
950 if let selected {
951 Button("Restore this version") {
952 do { restored(try workspace.restoreRevision(selected, to: record)) }
953 catch { message = error.localizedDescription }
954 }
955 .modifier(PrimaryActionStyle())
956 .accessibilityIdentifier("history.restore")
957 }
958 }
959 Text("Every save keeps a snapshot. Restoring creates a new version and keeps the versions that came after it.")
960 .font(.callout).foregroundStyle(palette.muted)
961 HStack(alignment: .top, spacing: 20) {
962 ScrollView {
963 VStack(alignment: .leading, spacing: 10) {
964 ForEach(revisions) { revision in
965 Button {
966 selectedID = revision.id
967 } label: {
968 VStack(alignment: .leading, spacing: 4) {
969 Text(revision.savedAt.flatMap(scheduleDate).map { $0.formatted(date: .abbreviated, time: .standard) } ?? "Earlier version")
970 .font(.callout.weight(.semibold))
971 Text(revision.source).font(.caption).foregroundStyle(palette.muted)
972 Text(revision.title).font(.caption).lineLimit(2)
973 }
974 .frame(maxWidth: .infinity, alignment: .leading)
975 .padding(12).studioSurface()
976 }
977 .buttonStyle(.plain)
978 }
979 }
980 }.frame(width: 230)
981 StudioRule(axis: .vertical)
982 ScrollView {
983 if let selected {
984 VStack(alignment: .leading, spacing: 18) {
985 Text(selected.title).font(.title2.bold())
986 if let subtitle = selected.subtitle, !subtitle.isEmpty { Text(subtitle) }
987 if ["thread", "followup"].contains(selected.format ?? "") {
988 let posts = XThreadText.posts(in: selected.text)
989 ForEach(posts.indices, id: \.self) { index in
990 Text(index == 0 ? "Opening post" : "Follow-up reply \(index)").font(.headline)
991 Text(posts[index]).textSelection(.enabled)
992 }
993 } else { Text(selected.text).textSelection(.enabled) }
994 }
995 .font(.body).lineSpacing(6)
996 .frame(maxWidth: .infinity, alignment: .leading)
997 .padding(16).studioSurface()
998 } else { Text("No saved revisions yet.").foregroundStyle(palette.muted) }
999 }
1000 }
1001 if let message { Text(message).font(.callout).foregroundStyle(palette.danger) }
1002 }
1003 .padding(24)
1004 .task {
1005 do {
1006 revisions = try workspace.revisionHistory(for: record)
1007 selectedID = revisions.first?.id
1008 } catch { message = error.localizedDescription }
1009 }
1010 }
1011}
1012
1013struct DraftStudio: View {
1014 @Environment(\.studioPalette) private var palette
1015 private var writingAgent: StudioChatAgent { .writingAgent(settings: workspace.settings) }
1016 @State var initial: WorkspaceRecord
1017 let workspace: Workspace
1018 let onDirty: (Bool) -> Void
1019 let showSchedule: (WorkspaceRecord) -> Void
1020 let reviewPublication: (WorkspaceRecord, Date?, @escaping (WorkspaceRecord) -> Void) -> Void
1021 let isActive: Bool
1022 let openArticle: (WorkspaceRecord, WorkspaceRecord) -> Void
1023 @Environment(\.openURL) private var openURL
1024 @State private var dirty = false
1025 @State private var generation: Task<Void, Never>?
1026 @State private var generationStatus = "Generating…"
1027 @State private var imageProviderConnected = false
1028 @State private var selectedSources: Set<String> = []
1029 @State private var promptDirection = ""
1030 @State private var rewriteNotes = ""
1031 @State private var linkedInDestinations: [LinkedInDestination] = []
1032 @State private var showsImageGeneration = false
1033 @State private var mediaChoice: DraftMediaKind?
1034 @State private var mediaPreview: DraftMediaPreview?
1035
1036 init(initial: WorkspaceRecord, workspace: Workspace, onDirty: @escaping (Bool) -> Void,
1037 showSchedule: @escaping (WorkspaceRecord) -> Void,
1038 reviewPublication: @escaping (WorkspaceRecord, Date?, @escaping (WorkspaceRecord) -> Void) -> Void,
1039 isActive: Bool, openArticle: @escaping (WorkspaceRecord, WorkspaceRecord) -> Void) {
1040 var draft = initial
1041 if !draft["title"].isEmpty { draft["title"] = draft.draftTitle }
1042 _initial = State(initialValue: draft)
1043 self.workspace = workspace
1044 self.onDirty = onDirty
1045 self.showSchedule = showSchedule
1046 self.reviewPublication = reviewPublication
1047 self.isActive = isActive
1048 self.openArticle = openArticle
1049 }
1050
1051 var body: some View {
1052 StudioScrollView {
1053 VStack(alignment: .leading, spacing: 22) {
1054 HStack {
1055 PageHeading(title: initial["format"] == "reply" ? "Have the last word." : "Find the words.", titleSize: 32)
1056 Spacer()
1057 if let reference = initial.referenceID {
1058 StudioCopyReference(reference: reference)
1059 }
1060 Button(action: { save() }) {
1061 HStack(alignment: .center, spacing: 7) {
1062 Image(systemName: "square.and.arrow.down")
1063 .font(.system(size: 13, weight: .semibold))
1064 .frame(width: 15, height: 15)
1065 .offset(y: -1)
1066 .accessibilityHidden(true)
1067 Text("Save draft")
1068 }
1069 }
1070 .modifier(PrimaryActionStyle())
1071 .keyboardShortcut("s")
1072 }
1073 HStack(spacing: 15) {
1074 StudioChoicePicker(title: "Platform", selection: value("platform"),
1075 options: ["x", "linkedin", "instagram", "reddit", "tiktok"],
1076 label: platformName, icon: PlatformMark.image)
1077 .disabled(initial.fields["manualQuote"] as? Bool == true)
1078 StudioFilterMenu(title: "Post format", value: XPostStyle(rawValue: initial["format"])?.title ?? initial["format"].capitalized) {
1079 Picker("Format", selection: value("format")) {
1080 ForEach(formats, id: \.self) { Text(XPostStyle(rawValue: $0)?.title ?? $0.capitalized).tag($0) }
1081 }
1082 .pickerStyle(.inline)
1083 }
1084 Spacer()
1085 }
1086 .onChange(of: initial["platform"]) { _, _ in
1087 if !formats.contains(initial["format"]) { initial["format"] = formats[0] }
1088 }
1089 if initial["platform"] == "linkedin" { linkedInOptions }
1090 if initial["platform"] == "x", !["posting", "posted"].contains(initial.scheduleStatus) {
1091 let canCreate = !initial.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && initial["format"] != "reply"
1092 let create: (() -> Void)? = canCreate ? { createLinkedArticle() } : nil
1093 PostArticlePicker(workspace: workspace, projectID: initial.projectID,
1094 articleID: value("xArticleID"), openArticle: openAttachedArticle,
1095 createArticle: create,
1096 xReplyArticles: workspace.xReplyArticles(for: initial, body: initial.body))
1097 }
1098 if initial["format"] == "reply" {
1099 HStack {
1100 TextField("X post link", text: replyValue("url"), prompt: draftPrompt("X post link", color: palette.muted))
1101 .studioInput()
1102 Button("Fetch post") { fetchReplyTarget() }
1103 .disabled(generation != nil || (initial.fields["replyTo"] as? [String: String])?["url"]?.isEmpty != false)
1104 }
1105 TextField("Original post text", text: replyValue("text"),
1106 prompt: draftPrompt("Original post text", color: palette.muted), axis: .vertical)
1107 .studioInput()
1108 }
1109 if workspace.writingToolsAvailable { generationControls }
1110 StudioRule()
1111 DraftTitleField(title: value("title"))
1112 mediaSection
1113 if workspace.agentConnected, !["posting", "posted"].contains(initial.scheduleStatus) {
1114 StudioProofreadAction(document: .init(title: initial["title"], body: initial.body),
1115 check: { try await ContentStudio.proofread($0, workspace: workspace) }) {
1116 initial["title"] = $0.title
1117 initial["content"] = $0.body
1118 }
1119 }
1120 DraftPostText(workspace: workspace, record: initial, text: value("content"), format: value("format"), label: "Post text", minHeight: 260)
1121 if workspace.writingToolsAvailable, !initial.body.isEmpty, !["posting", "posted"].contains(initial.scheduleStatus) {
1122 rewriteControls
1123 }
1124 StudioRule()
1125 VStack(alignment: .leading, spacing: 10) {
1126 HStack {
1127 Text("\(initial["content"].count) characters").foregroundStyle(.secondary)
1128 Spacer()
1129 Button("Copy text", systemImage: "doc.on.doc") { copy(initial["content"]) }
1130 Button("Export Markdown…") {
1131 saveMarkdown(title: initial.title, contents: "# \(initial.title)\n\n\(initial["content"])") {
1132 workspace.error = $0
1133 }
1134 }
1135 }
1136 ViewThatFits(in: .horizontal) {
1137 HStack { draftActions }
1138 VStack(alignment: .leading, spacing: 6) { draftActions }
1139 }
1140 }
1141 }
1142 .disabled(generation != nil)
1143 .studioPage()
1144 }
1145 .overlay(alignment: .topTrailing) {
1146 if generation != nil {
1147 HStack {
1148 ProgressView().controlSize(.small)
1149 Text(generationStatus)
1150 Button("Cancel") { generation?.cancel() }
1151 }
1152 .padding(10)
1153 .studioSurface(fill: palette.panel)
1154 .padding(15)
1155 }
1156 }
1157 .modifier(InkspringRatingPrompt(isIdle: isActive && !dirty && generation == nil && workspace.error == nil))
1158 .onAppear {
1159 selectedSources = Set(initial.fields["sourceIds"] as? [String] ?? [])
1160 }
1161 .onDisappear { generation?.cancel() }
1162 .task(id: providers.imageProvider) {
1163 imageProviderConnected = providers.imageProvider.isSaved
1164 }
1165 .sheet(item: $mediaPreview) { preview in
1166 DraftMediaSheet(preview: preview).studioAppearance(palette)
1167 }
1168 }
1169
1170 private var linkedInOptions: some View {
1171 let saved = LinkedInDestination(fields: initial.fields["linkedinDestination"] as? [String: Any])
1172 return VStack(alignment: .leading, spacing: 12) {
1173 HStack(spacing: 8) {
1174 Text("LinkedIn destination")
1175 StudioFilterMenu(title: "LinkedIn destination", value: saved?.name ?? "Connected personal profile") {
1176 Picker("LinkedIn destination", selection: linkedInDestination) {
1177 Text("Connected personal profile").tag("")
1178 if let saved, !linkedInDestinations.contains(where: { $0.id == saved.id }) {
1179 Text(saved.name).tag(saved.id)
1180 }
1181 ForEach(linkedInDestinations) { item in Text(item.name).tag(item.id) }
1182 }
1183 .pickerStyle(.inline)
1184 }
1185 }
1186 }
1187 .task { linkedInDestinations = (try? workspace.socialAccounts.savedLinkedInDestinations()) ?? [] }
1188 }
1189
1190 private func createLinkedArticle() {
1191 save()
1192 guard !dirty, workspace.error == nil else { return }
1193 workspace.perform {
1194 let article = try workspace.linkedArticleDraft(from: initial)
1195 if let current = workspace.drafts.first(where: { $0.id == initial.id }) { initial = current }
1196 openArticle(article, initial)
1197 }
1198 }
1199
1200 private func openAttachedArticle(_ article: WorkspaceRecord) {
1201 if dirty || !workspace.drafts.contains(where: { $0.id == initial.id }) {
1202 save()
1203 guard !dirty, workspace.error == nil else { return }
1204 }
1205 openArticle(article, initial)
1206 }
1207
1208 @ViewBuilder private var draftActions: some View {
1209 if initial.fields["manualQuote"] as? Bool != true,
1210 let platform = SocialPlatform(rawValue: initial["platform"]), SocialPublishPlan.supported.contains(platform) {
1211 Button("Post now…", systemImage: "paperplane") { openPublishReview() }
1212 .modifier(PrimaryActionStyle())
1213 .disabled(!initial.offersPostNow)
1214 .accessibilityIdentifier("post.now")
1215 }
1216 if initial.fields["manualQuote"] as? Bool != true, !["posting", "posted"].contains(initial.scheduleStatus) {
1217 Button(["queued", "due"].contains(initial.scheduleStatus) ? "View schedule" : "Ready to schedule") {
1218 save(toSchedule: true)
1219 }
1220 .disabled(initial.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
1221 }
1222 if workspace.quoteComposerURL(for: initial) != nil {
1223 Button {
1224 if dirty {
1225 save()
1226 guard !dirty else { return }
1227 }
1228 workspace.perform {
1229 let url = try workspace.prepareManualQuote(initial)
1230 if let latest = workspace.drafts.first(where: { $0.id == initial.id }) {
1231 initial = latest
1232 }
1233 openURL(url)
1234 }
1235 } label: {
1236 StudioLinkOutLabel { Text("Open quote in X…") }
1237 }
1238 }
1239 }
1240
1241 private func openPublishReview() {
1242 if dirty || !workspace.drafts.contains(where: { $0.id == initial.id }) {
1243 save()
1244 guard !dirty, workspace.error == nil else { return }
1245 }
1246 workspace.perform {
1247 try workspace.reload()
1248 guard let current = workspace.drafts.first(where: { $0.id == initial.id }),
1249 current["updatedAt"] == initial["updatedAt"] else {
1250 throw WorkspaceError("The draft changed. Reopen it before publishing.")
1251 }
1252 reviewPublication(current, nil) { _ in
1253 if var updated = workspace.drafts.first(where: { $0.id == current.id }) {
1254 updated["title"] = updated.draftTitle
1255 initial = updated
1256 }
1257 }
1258 }
1259 }
1260
1261 private var generationControls: some View {
1262 VStack(alignment: .leading, spacing: 10) {
1263 if initial["format"] != "reply" {
1264 VStack(alignment: .leading, spacing: 8) {
1265 draftFieldLabel("Writing brief")
1266 TextField("Writing brief", text: value("brief"),
1267 prompt: draftPrompt("What do you want to write about?", color: palette.muted), axis: .vertical)
1268 .font(InkspringTypography.interface(13))
1269 .lineSpacing(3)
1270 .lineLimit(2...5)
1271 .textFieldStyle(.plain)
1272 .padding(11)
1273 .studioSurface(StudioRadius.control)
1274 }
1275 }
1276 ViewThatFits(in: .horizontal) {
1277 HStack(spacing: 8) { generationButtons }
1278 VStack(alignment: .leading, spacing: 8) { generationButtons }
1279 }
1280
1281 DisclosureGroup("Generation options") {
1282 VStack(alignment: .leading, spacing: 8) {
1283 let tones = ["", "Plainspoken", "Curious", "Opinionated", "Technical", "Warm", "Wry", "Witty"]
1284 StudioChoicePicker(title: "Voice", selection: value("tone"),
1285 options: tones.contains(initial["tone"]) ? tones : tones + [initial["tone"]],
1286 label: { $0.isEmpty ? "My saved voice" : $0 })
1287 if initial["format"] == "reply" {
1288 TextField("Additional direction for your reply", text: value("brief"),
1289 prompt: draftPrompt("Additional direction for your reply", color: palette.muted), axis: .vertical)
1290 .lineLimit(2...5)
1291 .studioInput()
1292 }
1293 if !workspace.sources.isEmpty {
1294 StudioFilterMenu(title: "References", value: "References (\(selectedSources.count) selected)") {
1295 ForEach(workspace.sources) { source in
1296 Toggle(source.title, isOn: Binding(get: { selectedSources.contains(source.id) }, set: { included in
1297 if included && selectedSources.count < 6 { selectedSources.insert(source.id) }
1298 else if !included { selectedSources.remove(source.id) }
1299 initial.fields["sourceIds"] = selectedSources.sorted()
1300 markDirty()
1301 }))
1302 }
1303 }
1304 }
1305 }
1306 .frame(maxWidth: .infinity, alignment: .leading)
1307 .padding(.top, 8)
1308 }
1309 }
1310 }
1311
1312 @ViewBuilder private var generationButtons: some View {
1313 let connection = StudioWritingConnection(settings: workspace.settings)
1314 Button(action: generateDraft) {
1315 if connection == .agent {
1316 StudioAgentLabel(agent: writingAgent, title: "Generate with \(writingAgent.title)")
1317 } else {
1318 StudioPlatformLabel(name: providers.writingProvider.rawValue, title: "Generate with \(providers.writingProvider.name)")
1319 }
1320 }
1321 .modifier(PrimaryActionStyle())
1322 .disabled(!canGenerateDraft || (connection == .agent && ["queued", "due"].contains(initial.scheduleStatus)))
1323 .fixedSize()
1324 }
1325
1326 private var canGenerateDraft: Bool {
1327 guard !["posting", "posted"].contains(initial.scheduleStatus) else { return false }
1328 if initial["format"] == "reply" {
1329 let original = (initial.fields["replyTo"] as? [String: String])?["text"] ?? ""
1330 return !original.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1331 }
1332 return !initial["brief"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1333 }
1334
1335 private var attachedKinds: [DraftMediaKind] {
1336 DraftMediaKind.allCases.filter { initial.fields[$0.rawValue] is [String: Any] }
1337 }
1338
1339 private var mediaSection: some View {
1340 let attached = attachedKinds
1341 let selection = mediaChoice ?? (attached.count == 1 ? attached.first : nil)
1342 return VStack(alignment: .leading, spacing: 20) {
1343 Text("Media")
1344 .font(InkspringTypography.interface(13).weight(.semibold))
1345 .accessibilityAddTraits(.isHeader)
1346 let picker = StudioChoicePicker(title: "Media type", selection: Binding(get: { selection }, set: { choice in
1347 mediaChoice = choice
1348 showsImageGeneration = false
1349 }), options: [nil, .image, .video], label: { $0?.title ?? "Choose image or video" })
1350 ViewThatFits(in: .horizontal) {
1351 HStack(spacing: 8) {
1352 picker
1353 mediaActions(for: selection)
1354 }
1355 VStack(alignment: .leading, spacing: 8) {
1356 picker
1357 mediaActions(for: selection)
1358 }
1359 }
1360 if attached.count == 2 {
1361 Text("This draft has two attachments. Choose which one to keep before saving.")
1362 .font(.callout).foregroundStyle(.secondary)
1363 if let selection, let attachment = initial.fields[selection.rawValue] as? [String: Any] {
1364 Button("Keep \(selection.title.lowercased())", systemImage: "checkmark") {
1365 setAttachment(attachment, as: selection)
1366 }
1367 }
1368 }
1369 if let selection, attached.count == 1, attached.first != selection {
1370 Text("Adding \(selection == .image ? "an image" : "a video") replaces the attached \(attached[0].rawValue).")
1371 .font(.callout).foregroundStyle(.secondary)
1372 }
1373 if selection == .image, showsImageGeneration {
1374 if !imageProviderConnected {
1375 Text("Add an OpenAI or Gemini key in Settings → API keys to generate images.")
1376 .font(InkspringTypography.interface(12))
1377 .foregroundStyle(.secondary)
1378 }
1379 imageControls
1380 .onAppear {
1381 if workspace.writingToolsAvailable, initial["imagePrompt"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, hasImageContext {
1382 runGeneration("Writing image prompt…") { try await prepareImagePrompt() }
1383 }
1384 }
1385 .onChange(of: hasImageContext) { _, hasContext in
1386 if workspace.writingToolsAvailable, hasContext, initial["imagePrompt"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1387 runGeneration("Writing image prompt…") { try await prepareImagePrompt() }
1388 }
1389 }
1390 }
1391 if attached.contains(.image), attached.count == 1 || selection == .image {
1392 mediaRow("Image", kind: .image, url: workspace.imageURL(initial),
1393 previewOnly: !["image", "reply"].contains(initial["format"]))
1394 }
1395 if let video = initial.fields["video"] as? [String: Any], attached.count == 1 || selection == .video {
1396 mediaRow(video["name"] as? String ?? "Video", kind: .video, url: workspace.videoURL(initial),
1397 previewOnly: initial["format"] != "video" && !initial.needsNativePostVideo)
1398 if initial["platform"] == "tiktok" {
1399 HStack(spacing: 10) {
1400 Text("Cover frame")
1401 TextField("Seconds", text: value("tiktokCoverTime"))
1402 .studioInput()
1403 .frame(width: 100)
1404 .accessibilityLabel("TikTok cover frame in seconds")
1405 Text("seconds into the video").foregroundStyle(.secondary)
1406 }
1407 .help("TikTok uses a frame from the video as its cover. Leave blank to use TikTok’s default.")
1408 }
1409 }
1410 }
1411 .frame(maxWidth: .infinity, alignment: .leading)
1412 .padding(20)
1413 .studioSurface()
1414 }
1415
1416 @ViewBuilder private func mediaActions(for selection: DraftMediaKind?) -> some View {
1417 switch selection {
1418 case .image: imageActions
1419 case .video:
1420 Button(attachedKinds.contains(.video) ? "Replace video…" : "Attach video…",
1421 systemImage: "video", action: attachVideo)
1422 case nil: EmptyView()
1423 }
1424 }
1425
1426 @ViewBuilder private var imageActions: some View {
1427 Button("Generate image…", systemImage: "sparkles") { showsImageGeneration.toggle() }
1428 .accessibilityValue(showsImageGeneration ? "Expanded" : "Collapsed")
1429 Button(attachedKinds.contains(.image) ? "Replace image…" : "Attach image…", systemImage: "photo") {
1430 guard let url = workspace.chooseMedia([.png, .jpeg, .webP]) else { return }
1431 workspace.perform {
1432 setAttachment(try workspace.attachImage(url), as: .image)
1433 }
1434 }
1435 }
1436
1437 private func setAttachment(_ attachment: [String: Any], as kind: DraftMediaKind) {
1438 initial.setDraftMedia(attachment, as: kind)
1439 if kind == .image, ["post", "video"].contains(initial["format"]), formats.contains("image") {
1440 initial["format"] = "image"
1441 }
1442 if kind == .video {
1443 if formats.contains("video") { initial["format"] = "video" }
1444 else if initial["format"] == "image", formats.contains("post") { initial["format"] = "post" }
1445 }
1446 markDirty()
1447 }
1448
1449 private func mediaRow(_ title: String, kind: DraftMediaKind, url: URL?, previewOnly: Bool) -> some View {
1450 let available = url.flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }
1451 let thumbnail = kind == .video ? workspace.videoThumbnailURL(initial) : nil
1452 return HStack(spacing: 12) {
1453 if let available {
1454 Button { mediaPreview = DraftMediaPreview(title: title, url: available) } label: {
1455 DraftMediaThumbnail(url: available, kind: kind, customImage: thumbnail)
1456 }
1457 .buttonStyle(.plain)
1458 .accessibilityLabel("Preview \(kind.rawValue)")
1459 .help("Preview \(kind.rawValue)")
1460 } else {
1461 Image(systemName: kind.symbol)
1462 .foregroundStyle(.secondary)
1463 .frame(width: 106, height: 66)
1464 .studioSurface(StudioRadius.row)
1465 .accessibilityHidden(true)
1466 }
1467 VStack(alignment: .leading, spacing: 5) {
1468 Text(title)
1469 .font(InkspringTypography.interface(13).weight(.medium))
1470 .lineLimit(1)
1471 .truncationMode(.middle)
1472 .help(title)
1473 if available == nil {
1474 Text("File unavailable")
1475 .font(InkspringTypography.interface(12))
1476 .foregroundStyle(.secondary)
1477 } else if previewOnly {
1478 Text("Preview only")
1479 .font(InkspringTypography.interface(12))
1480 .foregroundStyle(.secondary)
1481 .help("The selected post format won’t publish this \(kind.rawValue).")
1482 }
1483 }
1484 .frame(maxWidth: .infinity, alignment: .leading)
1485 StudioMoreMenu(title: "\(kind.title) actions") {
1486 if kind == .video, initial["platform"] != "x" {
1487 let cover = switch initial["platform"] {
1488 case "instagram": "Reel cover"
1489 case "linkedin": "video thumbnail"
1490 default: "preview thumbnail"
1491 }
1492 Button("\(thumbnail == nil ? "Choose" : "Replace") \(cover)…", systemImage: "photo") {
1493 guard let url = workspace.chooseMedia([.png, .jpeg, .webP]) else { return }
1494 workspace.perform {
1495 initial.fields["videoThumbnail"] = try workspace.attachImage(url)
1496 markDirty()
1497 }
1498 }
1499 if thumbnail != nil {
1500 Button("Use video frame") {
1501 initial.fields["videoThumbnail"] = nil
1502 markDirty()
1503 }
1504 }
1505 Divider()
1506 } else if kind == .image, let available {
1507 Button("Copy image") {
1508 guard let image = NSImage(contentsOf: available), image.isValid else {
1509 workspace.error = "The attached image couldn’t be opened."
1510 return
1511 }
1512 NSPasteboard.general.clearContents()
1513 NSPasteboard.general.writeObjects([image])
1514 }
1515 Button("Save image…") { saveImage(available) }
1516 Divider()
1517 }
1518 Button("Remove \(kind.rawValue)", systemImage: "trash", role: .destructive) {
1519 initial.fields[kind.rawValue] = nil
1520 if kind == .video {
1521 initial.fields["videoThumbnail"] = nil
1522 initial.fields["tiktokCoverTime"] = nil
1523 }
1524 markDirty()
1525 }
1526 }
1527 }
1528 }
1529
1530 private var imageControls: some View {
1531 VStack(alignment: .leading, spacing: 8) {
1532 TextField("Image prompt", text: value("imagePrompt"),
1533 prompt: draftPrompt("Image prompt", color: palette.muted), axis: .vertical)
1534 .lineLimit(2...5)
1535 .textFieldStyle(.plain)
1536 .padding(12)
1537 .studioSurface(StudioRadius.control)
1538 Text(hasImageContext
1539 ? "Your writing connection creates the prompt from this draft. You can edit it before generating the image."
1540 : "Add a writing brief or post text to create an image prompt automatically.")
1541 .font(InkspringTypography.interface(12))
1542 .foregroundStyle(.secondary)
1543 TextField("Optional direction for a new prompt", text: $promptDirection,
1544 prompt: draftPrompt("Optional direction for a new prompt", color: palette.muted))
1545 .studioInput()
1546 HStack {
1547 if workspace.writingToolsAvailable {
1548 Button("Regenerate prompt", systemImage: "arrow.clockwise") {
1549 runGeneration("Writing image prompt…") { try await prepareImagePrompt(regenerate: true) }
1550 }
1551 .disabled(!hasImageContext)
1552 }
1553 Button("Generate image", systemImage: "sparkles") {
1554 runGeneration {
1555 try await prepareImagePrompt()
1556 let profile = workspace.settings["personalProfile"] as? [String: Any] ?? [:]
1557 let visualStyle = ["imageStyle", "avoid"].compactMap { profile[$0] as? String }.joined(separator: "\n")
1558 let prompt = [initial["imagePrompt"], visualStyle].filter { !$0.isEmpty }.joined(separator: "\n\n")
1559 let (bytes, fileExtension) = try await providers.image(prompt: prompt)
1560 try Task.checkCancellation()
1561 let file = try workspace.writeGeneratedImage(bytes, fileExtension: fileExtension)
1562 setAttachment(["file": file, "origin": providers.imageProvider.name,
1563 "prompt": initial["imagePrompt"]], as: .image)
1564 }
1565 }
1566 .disabled(!imageProviderConnected || ((!hasImageContext || !workspace.writingToolsAvailable) && initial["imagePrompt"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
1567 }
1568 }
1569 }
1570
1571 private var hasImageContext: Bool {
1572 ![initial["content"], initial["brief"]].joined().trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1573 }
1574
1575 private func prepareImagePrompt(regenerate: Bool = false) async throws {
1576 guard regenerate || initial["imagePrompt"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
1577 let input: [String: Any] = [
1578 "project": projectContext, "post": initial["content"], "brief": initial["brief"],
1579 "previousPrompt": initial["imagePrompt"], "requestedChanges": promptDirection
1580 ]
1581 let prompt = try await ContentStudio(workspace: workspace).model.prompt(input)
1582 try Task.checkCancellation()
1583 initial["imagePrompt"] = prompt
1584 markDirty()
1585 }
1586
1587 private var rewriteControls: some View {
1588 DisclosureGroup("Rewrite with notes") {
1589 VStack(alignment: .leading, spacing: 8) {
1590 TextField("Revision notes", text: $rewriteNotes,
1591 prompt: draftPrompt("Revision notes", color: palette.muted), axis: .vertical).lineLimit(2...5)
1592 if !initial["notesReply"].isEmpty {
1593 Text(initial["notesReply"]).font(.caption).foregroundStyle(.secondary)
1594 }
1595 HStack {
1596 Button("Rewrite draft") {
1597 let draft = initial
1598 let notes = rewriteNotes
1599 runGeneration {
1600 initial = try await ContentStudio(workspace: workspace).rewrite(draft, notes: notes)
1601 rewriteNotes = ""
1602 dirty = false
1603 onDirty(false)
1604 }
1605 }
1606 .disabled(rewriteNotes.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
1607 rewriteNotes.utf16.count > 4_000)
1608 if !initial["previousContent"].isEmpty {
1609 Button("Restore earlier wording") {
1610 workspace.perform {
1611 initial = try ContentStudio(workspace: workspace).undoRewrite(initial)
1612 dirty = false
1613 onDirty(false)
1614 }
1615 }
1616 }
1617 }
1618 }
1619 .padding(.top, 8)
1620 }
1621 }
1622
1623 private var providers: WritingProviders { WritingProviders(settings: workspace.settings) }
1624
1625 private func fetchReplyTarget() {
1626 let original = initial.fields["replyTo"] as? [String: String] ?? [:]
1627 guard let address = original["url"], !address.isEmpty else { return }
1628 runGeneration {
1629 let target = try await fetchXPost(address, accounts: workspace.socialAccounts)
1630 try Task.checkCancellation()
1631 guard initial["format"] == "reply", (initial.fields["replyTo"] as? [String: String]) == original else {
1632 throw WorkspaceError("The reply target changed while fetching. Review it and try again.")
1633 }
1634 initial.fields["replyTo"] = target
1635 markDirty()
1636 }
1637 }
1638
1639 private func saveImage(_ source: URL) {
1640 let panel = NSSavePanel()
1641 panel.allowedContentTypes = [UTType(filenameExtension: source.pathExtension) ?? .image]
1642 let name = initial.title.replacingOccurrences(of: "/", with: "-")
1643 panel.nameFieldStringValue = String(name.prefix(100)) + "." + source.pathExtension
1644 guard panel.runModal() == .OK, let destination = panel.url else { return }
1645 workspace.perform {
1646 let info = try source.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
1647 guard info.isRegularFile == true, let size = info.fileSize, size <= 30_000_000 else {
1648 throw WorkspaceError("The attached image is unavailable.")
1649 }
1650 guard destination.standardizedFileURL != source.standardizedFileURL else { return }
1651 try Data(contentsOf: source).write(to: destination, options: .atomic)
1652 }
1653 }
1654
1655 private var projectContext: [String: Any] {
1656 let fields = workspace.project?.fields ?? [:]
1657 var context = fields.filter { ["name", "description", "audience", "voice"].contains($0.key) }
1658 context["personalStyle"] = workspace.settings["personalProfile"]
1659 return context
1660 }
1661
1662 private func generateDraft() {
1663 let draft = initial
1664 let studio = ContentStudio(workspace: workspace)
1665 runGeneration("Writing with \(studio.model.name)…") {
1666 let (saved, _) = try await studio.compose(draft, withImage: false) { textDraft in
1667 initial = textDraft
1668 selectedSources = Set(textDraft.fields["sourceIds"] as? [String] ?? [])
1669 dirty = false
1670 onDirty(false)
1671 }
1672 try Task.checkCancellation()
1673 initial = saved
1674 if mediaChoice == .image || saved["format"] == "image" {
1675 try await prepareImagePrompt()
1676 initial = try workspace.save(initial)
1677 dirty = false
1678 onDirty(false)
1679 }
1680 workspace.notice = "Draft saved"
1681 }
1682 }
1683
1684 private func runGeneration(_ status: String = "Generating…", _ work: @escaping @MainActor () async throws -> Void) {
1685 guard generation == nil else { return }
1686 generationStatus = status
1687 generation = Task { @MainActor in
1688 defer { generation = nil }
1689 do { try await work() }
1690 catch {
1691 if !Task.isCancelled { workspace.error = error.localizedDescription }
1692 }
1693 }
1694 }
1695
1696 private var formats: [String] {
1697 switch initial["platform"] {
1698 case "tiktok": ["image", "video"]
1699 case "instagram": ["image", "video"]
1700 case "x": ["post", "followup", "thread", "image", "reply"]
1701 case "reddit": ["post", "image"]
1702 default: ["post"]
1703 }
1704 }
1705
1706 private func value(_ key: String) -> Binding<String> {
1707 Binding(get: { initial[key] }, set: { initial[key] = $0; markDirty() })
1708 }
1709
1710 private var linkedInDestination: Binding<String> {
1711 Binding(get: {
1712 (initial.fields["linkedinDestination"] as? [String: Any])?["urn"] as? String ?? ""
1713 }, set: { urn in
1714 initial.fields["linkedinDestination"] = linkedInDestinations.first { $0.urn == urn }?.fields
1715 markDirty()
1716 })
1717 }
1718
1719 private func replyValue(_ key: String) -> Binding<String> {
1720 Binding(get: { (initial.fields["replyTo"] as? [String: String])?[key] ?? "" }, set: { value in
1721 var target = initial.fields["replyTo"] as? [String: String] ?? [:]
1722 target[key] = value
1723 initial.fields["replyTo"] = target
1724 markDirty()
1725 })
1726 }
1727
1728 private func markDirty() {
1729 if !dirty { dirty = true; onDirty(true) }
1730 }
1731
1732 private func save(toSchedule: Bool = false) {
1733 workspace.perform {
1734 var draft = initial
1735 guard attachedKinds.count < 2 else {
1736 throw WorkspaceError("Choose one attachment to keep before saving.")
1737 }
1738 let isNewWriting = !draft.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1739 && !workspace.records.contains { $0.id == draft.id }
1740 if draft["platform"] == "tiktok", draft["format"] == "video" {
1741 _ = try TikTokVideo.coverTimestamp(for: draft)
1742 }
1743 if draft["platform"] == "linkedin", isNewWriting {
1744 draft["content"] = PostHashtags.addSuggestions(to: draft.body, platform: draft["platform"])
1745 }
1746 draft.prepareDraftForSave()
1747 if toSchedule, !["queued", "due"].contains(draft.scheduleStatus) {
1748 draft.fields["schedule"] = ["status": "ready", "pickedAt": WorkspaceRecord.timestamp, "slotAt": ""]
1749 }
1750 initial = try workspace.save(draft)
1751 workspace.notice = toSchedule && initial.scheduleStatus == "ready" ? "Ready to schedule" : "Draft saved"
1752 dirty = false
1753 onDirty(false)
1754 if isNewWriting { InkspringReview.recordActivity() }
1755 if toSchedule { showSchedule(initial) }
1756 }
1757 }
1758
1759 private func attachVideo() {
1760 var types: [UTType] = [.mpeg4Movie, .quickTimeMovie]
1761 if let webM = UTType(filenameExtension: "webm") { types.append(webM) }
1762 if ["x", "linkedin", "instagram"].contains(initial["platform"]) { types = [.mpeg4Movie] }
1763 guard let url = workspace.chooseMedia(types) else { return }
1764 runGeneration("Checking video…") {
1765 let video = try await workspace.attachVideo(url)
1766 try Task.checkCancellation()
1767 setAttachment(video, as: .video)
1768 }
1769 }
1770}
1771
1772private struct DraftMediaThumbnail: View {
1773 let url: URL
1774 let kind: DraftMediaKind
1775 var customImage: URL?
1776 @State private var thumbnail: CGImage?
1777
1778 var body: some View {
1779 ZStack {
1780 if let thumbnail {
1781 Image(decorative: thumbnail, scale: 1).resizable().scaledToFit()
1782 } else if kind == .image {
1783 Image(systemName: kind.symbol)
1784 .foregroundStyle(.secondary)
1785 .frame(maxWidth: .infinity, maxHeight: .infinity)
1786 }
1787 if kind == .video {
1788 Image(systemName: "play.fill")
1789 .font(.system(size: 12, weight: .semibold))
1790 .foregroundStyle(.white)
1791 .frame(width: 30, height: 30)
1792 .background(.black.opacity(0.7), in: Circle())
1793 }
1794 }
1795 .frame(width: 106, height: 66)
1796 .studioSurface(StudioRadius.row)
1797 .clipShape(.rect(cornerRadius: StudioRadius.row))
1798 .task(id: customImage ?? url) {
1799 thumbnail = nil
1800 let result = await loadThumbnail()
1801 if !Task.isCancelled { thumbnail = result }
1802 }
1803 }
1804
1805 private func loadThumbnail() async -> CGImage? {
1806 if let imageURL = customImage ?? (kind == .image ? url : nil),
1807 let source = CGImageSourceCreateWithURL(imageURL as CFURL, nil),
1808 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
1809 kCGImageSourceCreateThumbnailFromImageAlways: true,
1810 kCGImageSourceCreateThumbnailWithTransform: true,
1811 kCGImageSourceThumbnailMaxPixelSize: 256
1812 ] as CFDictionary) {
1813 return image
1814 }
1815 if kind == .video, url.pathExtension.lowercased() != "webm" {
1816 let asset = AVURLAsset(url: url)
1817 let generator = AVAssetImageGenerator(asset: asset)
1818 generator.maximumSize = CGSize(width: 256, height: 256)
1819 generator.appliesPreferredTrackTransform = true
1820 let duration = (try? await asset.load(.duration).seconds) ?? 0
1821 let seconds = duration.isFinite && duration > 0 ? min(4, duration * 0.2) : 0
1822 if let frame = try? await generator.image(at: CMTime(seconds: seconds, preferredTimescale: 600)) {
1823 return frame.image
1824 }
1825 }
1826 let request = QLThumbnailGenerator.Request(fileAt: url, size: CGSize(width: 120, height: 75),
1827 scale: 2, representationTypes: .thumbnail)
1828 return try? await QLThumbnailGenerator.shared.generateBestRepresentation(for: request).cgImage
1829 }
1830}
1831
1832private struct DraftMediaPreview: Identifiable {
1833 let title: String
1834 let url: URL
1835 var id: URL { url }
1836}
1837
1838private struct DraftMediaSheet: View {
1839 let preview: DraftMediaPreview
1840 @Environment(\.dismiss) private var dismiss
1841
1842 var body: some View {
1843 VStack(alignment: .leading, spacing: 16) {
1844 HStack(spacing: 12) {
1845 Text(preview.title)
1846 .font(InkspringTypography.interface(13).weight(.medium))
1847 .lineLimit(1)
1848 .truncationMode(.middle)
1849 .help(preview.title)
1850 .accessibilityAddTraits(.isHeader)
1851 .frame(maxWidth: .infinity, alignment: .leading)
1852 Button("Close", systemImage: "xmark") { dismiss() }
1853 .labelStyle(.iconOnly)
1854 .buttonStyle(StudioIconButtonStyle())
1855 .help("Close preview")
1856 .keyboardShortcut(.cancelAction)
1857 }
1858 AttachedMedia(url: preview.url, videoHeight: 420)
1859 .frame(maxWidth: .infinity)
1860 .clipShape(.rect(cornerRadius: StudioRadius.control))
1861 }
1862 .padding(22)
1863 .frame(width: 660)
1864 }
1865}
1866
1867private func draftFieldLabel(_ title: String) -> some View {
1868 Text(title)
1869 .font(InkspringTypography.interface(12).weight(.semibold))
1870 .foregroundStyle(.secondary)
1871 .accessibilityHidden(true)
1872}
1873
1874private func draftPrompt(_ title: String, color: Color) -> Text {
1875 Text(title).font(InkspringTypography.interface(13)).foregroundColor(color)
1876}
1877
1878struct DraftTitleField: View {
1879 @Environment(\.studioPalette) private var palette
1880 @Binding var title: String
1881
1882 var body: some View {
1883 VStack(alignment: .leading, spacing: 8) {
1884 draftFieldLabel("Draft title")
1885 TextField("Draft title", text: $title,
1886 prompt: draftPrompt("Give this draft a title", color: palette.muted), axis: .vertical)
1887 .font(InkspringTypography.editorial(19))
1888 .lineSpacing(3)
1889 .lineLimit(1...5)
1890 .textFieldStyle(.plain)
1891 .accessibilityLabel("Draft title")
1892 .padding(11)
1893 .studioSurface(StudioRadius.control)
1894 }
1895 }
1896}
1897
1898private struct DraftPostText: View {
1899 let workspace: Workspace
1900 let record: WorkspaceRecord
1901 @Binding var text: String
1902 @Binding var format: String
1903 let label: String
1904 let minHeight: CGFloat
1905
1906 private var supportsFollowUp: Bool {
1907 record["platform"] == "x" && XPostStyle(rawValue: format) != nil
1908 && (record.fields["manualQuote"] as? Bool != true || format != "post")
1909 && record.fields["image"] == nil && record.fields["video"] == nil
1910 && !["posting", "posted"].contains(record.scheduleStatus)
1911 }
1912
1913 var body: some View {
1914 VStack(alignment: .leading, spacing: 8) {
1915 if supportsFollowUp {
1916 StudioXPostEditor(text: $text, format: $format, articles: workspace.records.compactMap { article in
1917 guard article.isXArticle, article.projectID == record.projectID, let ref = article.referenceID else { return nil }
1918 return XArticleChoice(id: ref, title: article.title)
1919 }, openingLimit: record.fields["longPost"] as? Bool == true ? 25_000 : 280)
1920 } else if PostHashtags.separateField(on: record["platform"]) {
1921 CaptionHashtagEditor(text: $text, platform: record["platform"], format: format, minHeight: minHeight)
1922 .id(record["platform"])
1923 } else {
1924 DraftBodyField(text: $text, label: label, minHeight: minHeight)
1925 }
1926 }
1927 }
1928}
1929
1930private struct CaptionHashtagEditor: View {
1931 @Binding var text: String
1932 let platform: String
1933 let format: String
1934 let minHeight: CGFloat
1935 @State private var managesSuggestions: Bool?
1936 @State private var hashtagInput: String?
1937
1938 var body: some View {
1939 DraftBodyField(text: caption, label: "Caption", minHeight: minHeight)
1940 HStack(spacing: 10) {
1941 draftFieldLabel("Hashtags")
1942 Spacer()
1943 Button("Suggest hashtags", systemImage: "sparkles") {
1944 let copy = PostHashtags.split(text).caption
1945 let tags = PostHashtags.suggestions(for: copy, platform: platform, format: format)
1946 guard !tags.isEmpty else { return }
1947 hashtagInput = nil
1948 managesSuggestions = true
1949 text = PostHashtags.join(copy, with: tags)
1950 }
1951 .disabled(PostHashtags.split(text).caption.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
1952 }
1953 TextField("Hashtags", text: hashtags, prompt: Text("#example, #yourtopic"))
1954 .studioInput()
1955 .help("Edit or remove the suggested hashtags. Separate tags with spaces or commas.")
1956 .accessibilityIdentifier("post.hashtags")
1957 .onChange(of: text) {
1958 if let hashtagInput, PostHashtags.parse(hashtagInput) != PostHashtags.split(text).hashtags {
1959 self.hashtagInput = nil
1960 }
1961 }
1962 }
1963
1964 private var caption: Binding<String> {
1965 Binding(get: { PostHashtags.split(text).caption }, set: { updated in
1966 let previous = PostHashtags.split(text)
1967 let entered = PostHashtags.split(updated)
1968 if !entered.hashtags.isEmpty {
1969 managesSuggestions = false
1970 hashtagInput = nil
1971 text = PostHashtags.join(entered.caption, with: entered.hashtags)
1972 } else if managesSuggestions ?? (previous.caption.isEmpty && previous.hashtags.isEmpty) {
1973 managesSuggestions = true
1974 text = PostHashtags.addSuggestions(to: updated, platform: platform, format: format)
1975 } else {
1976 text = PostHashtags.join(updated, with: previous.hashtags)
1977 }
1978 })
1979 }
1980
1981 private var hashtags: Binding<String> {
1982 Binding(get: { hashtagInput ?? PostHashtags.split(text).hashtags.joined(separator: " ") }, set: { input in
1983 managesSuggestions = false
1984 hashtagInput = input
1985 text = PostHashtags.join(PostHashtags.split(text).caption, with: PostHashtags.parse(input))
1986 })
1987 }
1988}
1989
1990struct DraftBodyField: View {
1991 @Environment(\.studioPalette) private var palette
1992 @FocusState private var editorFocused: Bool
1993 @State private var finding = false
1994 @Binding var text: String
1995 let label: String
1996 let minHeight: CGFloat
1997 var onFocusLost: (() -> Void)? = nil
1998 var focusRequest = 0
1999 var findRequest = 0
2000 var expandsWithDocument = false
2001
2002 var body: some View {
2003 VStack(alignment: .leading, spacing: 8) {
2004 HStack {
2005 draftFieldLabel(label)
2006 if !expandsWithDocument {
2007 Spacer()
2008 Button("Find", systemImage: "magnifyingglass") { finding.toggle() }
2009 .keyboardShortcut("f", modifiers: .command)
2010 .accessibilityIdentifier("editor.find")
2011 }
2012 }
2013 MacWritingTextView(text: $text, findRequest: (finding ? 1 : 0) + findRequest * 2, focusRequest: focusRequest, monospaced: label == "Markdown", documentMinimumHeight: expandsWithDocument ? minHeight : nil, onFocusLost: onFocusLost)
2014 .focused($editorFocused)
2015 .onChange(of: focusRequest) { editorFocused = true }
2016 .onChange(of: editorFocused) { previous, focused in
2017 if previous && !focused { onFocusLost?() }
2018 }
2019 .font(label == "Markdown" ? .system(size: 14, design: .monospaced) : InkspringTypography.interface(16))
2020 .lineSpacing(4)
2021 .frame(minHeight: minHeight, alignment: .topLeading)
2022 .accessibilityLabel(label)
2023 .scrollContentBackground(.hidden)
2024 .overlay(alignment: .topLeading) {
2025 if text.isEmpty {
2026 draftPrompt(label == "Idea and angle" ? "Describe the idea and angle…" : label == "Markdown" ? "Write in Markdown…" : "Write your post…", color: palette.muted)
2027 .padding(.leading, 5)
2028 .padding(.top, 3)
2029 .accessibilityHidden(true)
2030 .allowsHitTesting(false)
2031 }
2032 }
2033 .padding(14)
2034 .studioSurface()
2035 }
2036 }
2037}
2038
2039extension Workspace {
2040 func chooseMedia(_ types: [UTType]) -> URL? {
2041 let panel = NSOpenPanel()
2042 panel.allowedContentTypes = types
2043 let last = settings["lastMediaDirectory"] as? String
2044 let savedFolder = last.flatMap { $0.hasPrefix("/") ? URL(fileURLWithPath: $0, isDirectory: true) : nil }
2045 panel.directoryURL = [savedFolder, directory?.appending(path: "images", directoryHint: .isDirectory)]
2046 .compactMap { $0 }.first { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
2047 guard panel.runModal() == .OK, let url = panel.url else { return nil }
2048 perform { try set("lastMediaDirectory", to: url.deletingLastPathComponent().path) }
2049 return url
2050 }
2051}
2052
2053@MainActor
2054func saveMarkdown(title: String, contents: String, report: (String) -> Void) {
2055 let panel = NSSavePanel()
2056 panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]
2057 panel.nameFieldStringValue = title.replacingOccurrences(of: "/", with: "-") + ".md"
2058 guard panel.runModal() == .OK, let url = panel.url else { return }
2059 do { try contents.write(to: url, atomically: true, encoding: .utf8) }
2060 catch { report(error.localizedDescription) }
2061}