Branchwell

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

Raw 25.2 KB on 332c2458022ae8f6648ea05f3c733b528a595172
1import SwiftUI
2import InkspringSchedule
3import UniformTypeIdentifiers
4
5struct IdeaQueueView: View {
6 @Environment(\.studioPalette) private var palette
7 let workspace: Workspace
8 let add: () -> Void
9 let edit: (WorkspaceRecord) -> Void
10 let openDraft: (WorkspaceRecord) -> Void
11 let openNewsletter: (WorkspaceRecord) -> Void
12 let showAction: (WorkspaceRecord, IdeaAction) -> Void
13
14 @State private var filter = "draft"
15 @State private var busy = false
16 @State private var message: String?
17
18 private let cardSpacing: CGFloat = 20
19
20 private var ideas: [WorkspaceRecord] {
21 workspace.ideas.filter { matches($0, filter) }
22 }
23
24 private func matches(_ idea: WorkspaceRecord, _ tab: String) -> Bool {
25 idea["status"] == tab || tab == "picked" && !idea.draftVersions.isEmpty
26 }
27
28 var body: some View {
29 StudioScrollView {
30 VStack(alignment: .leading, spacing: 18) {
31 HStack {
32 PageHeading(title: "Post ideas", subtitle: "Develop an angle, then turn it into a post when it’s ready.")
33 Spacer()
34 if busy { ProgressView().controlSize(.small) }
35 if workspace.writingToolsAvailable {
36 Button("Refresh ideas", systemImage: "arrow.clockwise") { Task { await refresh() } }
37 .disabled(busy || workspace.project == nil)
38 }
39 Button("New idea", systemImage: "plus", action: add)
40 .modifier(PrimaryActionStyle())
41 }
42 StudioTabs(selection: $filter, tabs: ["draft", "picked"], label: tabLabel,
43 count: { status in workspace.ideas.filter { matches($0, status) }.count })
44 if let message { Text(message).foregroundStyle(.secondary).textSelection(.enabled) }
45 if ideas.isEmpty {
46 ContentUnavailableView(emptyTitle, systemImage: "newspaper")
47 .frame(maxWidth: .infinity)
48 } else {
49 LazyVGrid(columns: [GridItem(.adaptive(minimum: 320), spacing: cardSpacing)],
50 alignment: .leading, spacing: cardSpacing) {
51 ForEach(ideas) { idea in
52 ideaCard(idea)
53 }
54 }
55 }
56 }
57 .studioPage()
58 }
59 }
60
61 private func tabLabel(_ status: String) -> String {
62 switch status {
63 case "draft": "Open"
64 case "picked": "Drafted"
65 default: "Skipped"
66 }
67 }
68
69 private var emptyTitle: String {
70 switch filter {
71 case "draft": "No open ideas"
72 case "picked": "No ideas turned into drafts yet"
73 default: "No skipped ideas"
74 }
75 }
76
77 private func ideaCard(_ idea: WorkspaceRecord) -> some View {
78 VStack(alignment: .leading, spacing: 10) {
79 IdeaExcerpt(title: idea.title, text: idea.body)
80 if workspace.imageURL(idea) != nil {
81 Button { showAction(idea, .image) } label: {
82 Label("View image", systemImage: "photo")
83 }
84 .accessibilityIdentifier("idea.image.open")
85 }
86 Spacer(minLength: 3)
87 StudioRule()
88 switch filter == "picked" ? "picked" : idea["status"] {
89 case "draft":
90 draftActions(idea)
91 case "skipped":
92 HStack {
93 Button("Restore to Open", systemImage: "arrow.uturn.backward") { change(idea, to: "draft") }
94 Button("Edit idea…") { edit(idea) }
95 }
96 default:
97 linkedDrafts(idea)
98 if idea["status"] == "picked" {
99 Button("Reopen idea") { change(idea, to: "draft") }
100 }
101 }
102 }
103 .padding(15)
104 .frame(maxWidth: .infinity, alignment: .leading)
105 .studioSurface()
106 }
107
108 private func draftActions(_ idea: WorkspaceRecord) -> some View {
109 let links = idea.draftVersions.merging(idea.fields["mobileWritingVersions"] as? [String: String] ?? [:]) { current, _ in current }
110 let draft = Button("Draft from idea…", systemImage: "square.and.pencil") {
111 showAction(idea, .draft)
112 }
113 .modifier(PrimaryActionStyle())
114 .disabled(CompanionLibrary.draftPlatforms(hasIdeaImage: workspace.imageURL(idea) != nil).allSatisfy { links[$0] != nil })
115 let feedback = Button("Give feedback…") {
116 showAction(idea, .feedback)
117 }
118 let more = StudioMoreMenu(title: "More actions for \(idea.title)", size: 35) {
119 if workspace.imageURL(idea) == nil {
120 Button("Add image…", systemImage: "photo") { showAction(idea, .image) }
121 }
122 newsletterButton(idea)
123 Button("Edit idea…") { edit(idea) }
124 Button("Skip idea") { change(idea, to: "skipped") }
125 }
126 return ViewThatFits(in: .horizontal) {
127 HStack(spacing: 7) {
128 if workspace.writingToolsAvailable {
129 draft
130 feedback
131 }
132 Spacer(minLength: 0)
133 more
134 }
135 VStack(alignment: .leading, spacing: 8) {
136 HStack {
137 if workspace.writingToolsAvailable { draft }
138 Spacer(minLength: 0)
139 more
140 }
141 if workspace.writingToolsAvailable { feedback }
142 }
143 }
144 }
145
146 @ViewBuilder private func linkedDrafts(_ idea: WorkspaceRecord) -> some View {
147 let links = idea.fields["versions"] as? [String: String] ?? [:]
148 let drafts = links.keys.sorted().compactMap { platform in
149 workspace.drafts.first { $0.id == links[platform] }
150 }
151 if drafts.isEmpty {
152 VStack(alignment: .leading, spacing: 10) {
153 Text("No linked drafts in this workspace").font(.caption).foregroundStyle(.secondary)
154 newsletterButton(idea)
155 }
156 } else {
157 ViewThatFits(in: .horizontal) {
158 HStack(spacing: 8) { draftButtons(drafts); newsletterButton(idea) }
159 VStack(alignment: .leading, spacing: 9) {
160 HStack(spacing: 8) { draftButtons(drafts) }
161 newsletterButton(idea)
162 }
163 VStack(alignment: .leading, spacing: 9) {
164 draftButtons(drafts)
165 newsletterButton(idea)
166 }
167 }
168 }
169 }
170
171 private func draftButtons(_ drafts: [WorkspaceRecord]) -> some View {
172 ForEach(drafts) { draft in
173 Button("Open \(platformName(draft["platform"])) draft", systemImage: "arrow.up.right") {
174 openDraft(draft)
175 }
176 .fixedSize()
177 }
178 }
179
180 private func newsletterButton(_ idea: WorkspaceRecord) -> some View {
181 Button("Draft newsletter…", systemImage: "envelope") { openNewsletter(idea) }
182 .fixedSize()
183 }
184
185 private func change(_ idea: WorkspaceRecord, to state: String) {
186 workspace.perform {
187 if state == "skipped" { try workspace.trashLibraryItem(idea); return }
188 var idea = idea
189 idea["status"] = state
190 idea["skippedAt"] = state == "skipped" ? WorkspaceRecord.timestamp : ""
191 try workspace.save(idea)
192 }
193 }
194
195 private func refresh() async {
196 guard !busy, let project = workspace.project else { return }
197 busy = true
198 defer { busy = false }
199 do {
200 let result = try await ResearchDiscovery(studio: ContentStudio(workspace: workspace))
201 .refreshIdeas(projectID: project.id, withResearch: true)
202 guard project.id == workspace.projectID else { return }
203 let summary = "\(result.written) new ideas · \(result.open.count) open"
204 message = ([summary] + result.warnings).joined(separator: "\n")
205 filter = "draft"
206 } catch { workspace.error = error.localizedDescription }
207 }
208}
209
210private struct IdeaExcerpt: View {
211 @Environment(\.studioPalette) private var palette
212 let title: String
213 let text: String
214 @State private var expanded = false
215 @State private var visibleHeight: CGFloat = 0
216 @State private var fullHeight: CGFloat = 0
217
218 var body: some View {
219 VStack(alignment: .leading, spacing: 5) {
220 excerpt(limited: !expanded)
221 .onGeometryChange(for: CGFloat.self, of: { $0.size.height }) { visibleHeight = $0 }
222 .background(alignment: .topLeading) {
223 if !expanded {
224 excerpt(limited: false)
225 .hidden()
226 .accessibilityHidden(true)
227 .onGeometryChange(for: CGFloat.self, of: { $0.size.height }) { fullHeight = $0 }
228 }
229 }
230 if expanded || fullHeight > visibleHeight + 1 {
231 Button(expanded ? "Show less" : "Show more",
232 systemImage: expanded ? "chevron.up" : "chevron.down") { expanded.toggle() }
233 .buttonStyle(.plain)
234 .font(InkspringTypography.interface(13).weight(.medium))
235 .foregroundStyle(palette.accent)
236 .padding(.vertical, 4)
237 .accessibilityHint(expanded ? "Collapse this idea" : "Read the complete idea")
238 }
239 }
240 }
241
242 private func excerpt(limited: Bool) -> some View {
243 VStack(alignment: .leading, spacing: 10) {
244 Text(title)
245 .font(InkspringTypography.interface(22).weight(.semibold))
246 .lineSpacing(4)
247 .lineLimit(limited ? 2 : nil)
248 .accessibilityAddTraits(.isHeader)
249 Text(text)
250 .font(InkspringTypography.interface(14))
251 .lineSpacing(3)
252 .lineLimit(limited ? 5 : nil)
253 .foregroundStyle(.secondary)
254 .textSelection(.enabled)
255 }
256 .frame(maxWidth: .infinity, alignment: .leading)
257 .fixedSize(horizontal: false, vertical: true)
258 }
259}
260
261enum IdeaAction {
262 case draft, feedback, image
263
264 var title: String {
265 switch self {
266 case .draft: "Draft from idea"
267 case .feedback: "Give feedback"
268 case .image: "Idea image"
269 }
270 }
271}
272
273struct MacSavedIdeaPage: View {
274 let idea: WorkspaceRecord
275 let workspace: Workspace
276 let close: () -> Void
277 let edit: () -> Void
278 let draft: () -> Void
279 let media: (String) -> Void
280 let image: (WorkspaceRecord) -> Void
281
282 private var current: WorkspaceRecord { workspace.records.first { $0.id == idea.id } ?? idea }
283
284 var body: some View {
285 StudioEditorPage(title: "Post idea") {
286 Button("Done", action: close)
287 .keyboardShortcut(.cancelAction)
288 } content: {
289 StudioScrollView {
290 VStack(alignment: .leading, spacing: 18) {
291 Text(current.title).font(InkspringTypography.editorial(32, relativeTo: .title))
292 .accessibilityAddTraits(.isHeader)
293 Text(current.body).lineSpacing(3).textSelection(.enabled)
294 if let url = workspace.imageURL(current) { IdeaImagePreview(url: url) }
295 Button("Edit idea", systemImage: "pencil", action: edit)
296 if current["status"] == "draft" {
297 Button(workspace.imageURL(current) == nil ? "Add image…" : "Edit image…", systemImage: "photo") {
298 image(current)
299 }
300 Button("Draft from post idea", systemImage: "square.and.pencil", action: draft)
301 .modifier(PrimaryActionStyle())
302 Menu("Create media draft", systemImage: "photo.on.rectangle") {
303 Button("TikTok video") { media("tiktok") }
304 Button("Instagram post") { media("instagram") }
305 }
306 }
307 }
308 .frame(maxWidth: 760, alignment: .leading)
309 .studioPage()
310 }
311 }
312 }
313}
314
315struct MacQuickXPage: View {
316 @Environment(\.studioPalette) private var palette
317 let workspace: Workspace
318 let close: () -> Void
319 let review: (String) -> Void
320 @State private var text = ""
321
322 private var post: String { XThreadText.singlePost(text) }
323 private var valid: Bool { XThreadText.validSinglePost(post) }
324
325 var body: some View {
326 StudioEditorPage(title: "Quick X post") {
327 Button("Cancel", role: .cancel, action: close).keyboardShortcut(.cancelAction)
328 Button("Review on X") { review(post) }
329 .modifier(PrimaryActionStyle()).disabled(!valid)
330 } content: {
331 StudioScrollView {
332 VStack(alignment: .leading, spacing: 12) {
333 TextField("Your post", text: $text, prompt: Text("Write the one thing you want to say."), axis: .vertical)
334 .textFieldStyle(.plain).lineLimit(4...10)
335 .padding(12).studioSurface()
336 .accessibilityIdentifier("quickX.text")
337 Text("\(XThreadText.weight(post)) / 280").font(.caption).foregroundStyle(palette.muted)
338 StudioProofreadAction(document: .init(title: "", body: text),
339 unavailable: workspace.agentConnected ? nil : "Connect a writing agent to proofread.",
340 reviewInSheet: true,
341 check: { try await ContentStudio.proofread($0, workspace: workspace) }) { text = $0.body }
342 }
343 .frame(maxWidth: 650, alignment: .leading)
344 .studioPage()
345 }
346 }
347 }
348}
349
350struct IdeaActionPage: View {
351 @State var idea: WorkspaceRecord
352 let action: IdeaAction
353 let workspace: Workspace
354 let close: () -> Void
355 let completed: ([WorkspaceRecord]) -> Void
356
357 @Environment(\.studioPalette) private var palette
358 @State private var chosen: Set<String> = []
359 @State private var notes = ""
360 @State private var progress: String?
361 @State private var failure: Error?
362 @State private var imagePrompt = ""
363
364 private var busy: Bool { progress != nil }
365 private var linked: [String: String] {
366 idea.draftVersions.merging(idea.fields["mobileWritingVersions"] as? [String: String] ?? [:]) { current, _ in current }
367 }
368 private var createLabel: String {
369 switch chosen.count {
370 case 0: "Create drafts"
371 case 1: "Create 1 draft"
372 default: "Create \(chosen.count) drafts"
373 }
374 }
375
376 var body: some View {
377 StudioEditorPage(title: action.title) {
378 Button(action == .draft ? "Cancel" : "Done", role: .cancel, action: close)
379 .disabled(busy)
380 .keyboardShortcut(.cancelAction)
381 switch action {
382 case .draft:
383 Button(createLabel) { write(Array(chosen)) }
384 .modifier(PrimaryActionStyle())
385 .disabled(busy || chosen.isEmpty)
386 case .feedback:
387 Button("Apply feedback") { applyFeedback() }
388 .modifier(PrimaryActionStyle())
389 .disabled(busy || notes.utf16.count > 4000 || notes.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
390 case .image:
391 EmptyView()
392 }
393 } content: {
394 StudioScrollView {
395 VStack(alignment: .leading, spacing: 17) {
396 ideaPreview
397 switch action {
398 case .draft: platformChoices
399 case .feedback: feedbackEditor
400 case .image: imageEditor
401 }
402 feedbackStatus
403 }
404 .frame(maxWidth: 920, alignment: .leading)
405 .studioPage()
406 }
407 }
408 .onAppear {
409 imagePrompt = (idea.fields["image"] as? [String: String])?["prompt"] ?? ""
410 }
411 }
412
413 private var ideaPreview: some View {
414 VStack(alignment: .leading, spacing: 7) {
415 Text(idea.title).font(InkspringTypography.editorial(24, relativeTo: .title2))
416 .accessibilityAddTraits(.isHeader)
417 Text(idea.body).textSelection(.enabled).lineSpacing(3)
418 if !idea["mediaPlan"].isEmpty {
419 Label(idea["mediaPlan"], systemImage: "photo")
420 .font(.callout).foregroundStyle(palette.muted)
421 }
422 if let source = XQuoteComposer.source(in: idea) {
423 StudioExternalLink("View source on X", destination: source).font(.callout)
424 }
425 }
426 .frame(maxWidth: .infinity, alignment: .leading)
427 .padding(14)
428 .studioSurface()
429 }
430
431 private var platformChoices: some View {
432 VStack(alignment: .leading, spacing: 9) {
433 Text("Where should Inkspring write a draft?")
434 .font(InkspringTypography.interface(15).weight(.semibold))
435 .accessibilityAddTraits(.isHeader)
436 Text("You’ll get one editable draft per platform you select.")
437 .foregroundStyle(palette.muted)
438 if let url = workspace.imageURL(idea) {
439 IdeaImagePreview(url: url).frame(maxWidth: 240)
440 Label("The idea image is sized for each photo post you draft.", systemImage: "photo")
441 .font(.callout).foregroundStyle(palette.muted)
442 }
443 LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), alignment: .leading)], alignment: .leading, spacing: 12) {
444 ForEach(CompanionLibrary.draftPlatforms(hasIdeaImage: workspace.imageURL(idea) != nil), id: \.self) { platform in
445 if linked[platform] != nil {
446 StudioPlatformLabel(name: platform, title: platformName(platform) + " drafted")
447 .foregroundStyle(palette.muted)
448 } else {
449 Toggle(isOn: Binding(get: { chosen.contains(platform) }, set: { enabled in
450 if enabled { chosen.insert(platform) } else { chosen.remove(platform) }
451 })) {
452 StudioPlatformLabel(name: platform, title: platform == "tiktok" ? "TikTok photo" : platformName(platform),
453 iconOffset: platform == "linkedin" ? 1 : 0)
454 }
455 .disabled(busy)
456 }
457 }
458 }
459 .padding(.vertical, 4)
460 if XQuoteComposer.source(in: idea) != nil, linked["x"] == nil {
461 Button { write(["x"], manualQuote: true) } label: {
462 StudioPlatformLabel(name: "x", title: "Create X quote draft")
463 }
464 .disabled(busy)
465 .help("Draft a quote of the cited X post to finish in X.")
466 }
467 }
468 }
469
470 private var imageEditor: some View {
471 VStack(alignment: .leading, spacing: 12) {
472 let url = workspace.imageURL(idea)
473 if let url { IdeaImagePreview(url: url) }
474 if idea["status"] == "draft" {
475 TextField("Image direction (optional)", text: $imagePrompt, axis: .vertical)
476 .textFieldStyle(.plain).lineLimit(2...5).padding(10).studioSurface(StudioRadius.control)
477 .disabled(busy)
478 let provider = WritingProviders(settings: workspace.settings).imageProvider
479 ViewThatFits(in: .horizontal) {
480 HStack { imageActions(hasImage: url != nil, provider: provider) }
481 VStack(alignment: .leading) { imageActions(hasImage: url != nil, provider: provider) }
482 }
483 if !provider.isSaved {
484 Text("Add a \(provider.name) API key in Settings → API keys to generate an image.")
485 .font(.callout).foregroundStyle(palette.muted)
486 }
487 }
488 }
489 }
490
491 @ViewBuilder private func imageActions(hasImage: Bool, provider: ProviderKey) -> some View {
492 Button(hasImage ? "Regenerate image" : "Generate image", systemImage: "sparkles") {
493 Task { await run("Generating image…") {
494 idea = try await ContentStudio(workspace: workspace).makeIdeaImage(for: idea, prompt: imagePrompt)
495 } }
496 }
497 .modifier(PrimaryActionStyle())
498 .disabled(busy || !provider.isSaved || imagePrompt.utf16.count > 4000)
499 .accessibilityIdentifier("idea.image.generate")
500 Button(hasImage ? "Replace with file…" : "Attach image…", systemImage: "photo") {
501 guard let source = workspace.chooseMedia([.png, .jpeg, .webP]) else { return }
502 do {
503 idea = try ContentStudio(workspace: workspace).attachIdeaImage(source, to: idea)
504 failure = nil
505 } catch { failure = error }
506 }
507 .disabled(busy)
508 if hasImage {
509 Button("Remove image", systemImage: "trash") {
510 do {
511 idea = try ContentStudio(workspace: workspace).removeIdeaImage(from: idea)
512 failure = nil
513 } catch { failure = error }
514 }
515 .disabled(busy)
516 }
517 }
518
519 private var feedbackEditor: some View {
520 VStack(alignment: .leading, spacing: 9) {
521 Text("What should change about this idea?")
522 .font(InkspringTypography.interface(15).weight(.semibold))
523 .accessibilityAddTraits(.isHeader)
524 Text("Inkspring rewrites the idea using your feedback and saves the revision here.")
525 .foregroundStyle(palette.muted)
526 TextField("Example: Focus on a decision readers can try themselves", text: $notes, axis: .vertical)
527 .textFieldStyle(.plain)
528 .lineLimit(3...5)
529 .padding(9)
530 .studioSurface(StudioRadius.control)
531 .accessibilityLabel("Feedback on this idea")
532 .disabled(busy)
533 if !idea["notesReply"].isEmpty {
534 Label(idea["notesReply"], systemImage: "checkmark.circle")
535 .font(.callout).foregroundStyle(palette.muted)
536 }
537 if !idea["previousText"].isEmpty {
538 Button("Restore earlier wording") {
539 do {
540 idea = try ContentStudio(workspace: workspace).undoRewrite(idea)
541 failure = nil
542 } catch { failure = error }
543 }
544 .disabled(busy)
545 }
546 }
547 }
548
549 private var feedbackStatus: some View {
550 VStack(alignment: .leading, spacing: 9) {
551 if let failure {
552 Group {
553 if let failure = failure as? StudioAgentFailure {
554 StudioAgentLabel(agent: failure.agent, title: failure.localizedDescription)
555 } else {
556 Label(failure.localizedDescription, systemImage: "exclamationmark.circle")
557 }
558 }
559 .foregroundStyle(palette.danger)
560 .textSelection(.enabled)
561 .accessibilityAddTraits(.updatesFrequently)
562 }
563 if let progress {
564 HStack(spacing: 7) {
565 ProgressView().controlSize(.small)
566 Text(progress)
567 }
568 } else if action == .draft {
569 Label("Drafts go to Ready to schedule. You choose when they go out.", systemImage: "calendar")
570 .font(.callout).foregroundStyle(palette.muted)
571 }
572 }
573 }
574
575 private func applyFeedback() {
576 Task {
577 await run("Revising the idea…") {
578 idea = try await ContentStudio(workspace: workspace).rewrite(idea, notes: notes)
579 notes = ""
580 }
581 }
582 }
583
584 private func write(_ platforms: [String], manualQuote: Bool = false) {
585 Task {
586 await run(platforms.count == 1 ? "Writing your draft…" : "Writing your drafts…") {
587 let (_, drafts) = try await ContentStudio(workspace: workspace)
588 .pick(idea, platforms: platforms, manualQuote: manualQuote)
589 completed(drafts)
590 close()
591 }
592 }
593 }
594
595 private func run(_ status: String, work: () async throws -> Void) async {
596 guard !busy else { return }
597 progress = status
598 failure = nil
599 defer { progress = nil }
600 do { try await work() } catch { failure = error }
601 }
602}
603
604private struct IdeaImagePreview: View {
605 let url: URL
606
607 var body: some View {
608 if let preview = IdeaArtwork.preview(from: url), let image = NSImage(data: preview) {
609 Image(nsImage: image).resizable().scaledToFit()
610 .frame(maxWidth: 420, maxHeight: 300, alignment: .leading)
611 .clipShape(.rect(cornerRadius: StudioRadius.control))
612 .accessibilityLabel("Post idea image")
613 .accessibilityIdentifier("idea.image.preview")
614 }
615 }
616}