Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / WorkspaceWindow.swift
| 1 | import AppKit |
| 2 | import AVKit |
| 3 | import SwiftUI |
| 4 | import InkspringSchedule |
| 5 | import WebKit |
| 6 | |
| 7 | enum WorkspacePage: String, CaseIterable, Identifiable { |
| 8 | case ideas = "Post ideas", schedule = "Schedule", published = "Published", workspace = "Workspace" |
| 9 | case research = "Research", replies = "Replies", analytics = "Analytics" |
| 10 | case studio = "Writing studio", library = "Library" |
| 11 | case connections = "Connections", trash = "Trash", about = "About Inkspring", settings = "Settings" |
| 12 | |
| 13 | var id: Self { self } |
| 14 | |
| 15 | var icon: String { |
| 16 | switch self { |
| 17 | case .ideas: "newspaper" |
| 18 | case .schedule: "calendar.badge.clock" |
| 19 | case .published: "paperplane" |
| 20 | case .workspace: "folder" |
| 21 | case .research: "antenna.radiowaves.left.and.right" |
| 22 | case .replies: "bubble.left.and.bubble.right" |
| 23 | case .analytics: "chart.bar.xaxis" |
| 24 | case .studio: "pencil.and.outline" |
| 25 | case .library: "square.stack" |
| 26 | case .connections: "link" |
| 27 | case .trash: "trash" |
| 28 | case .about: "info.circle" |
| 29 | case .settings: "gearshape" |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | struct WorkspaceWindow: View { |
| 35 | private enum EditorRoute { |
| 36 | case record(WorkspaceRecord) |
| 37 | case savedIdea(WorkspaceRecord) |
| 38 | case quickX |
| 39 | case ideaAction(WorkspaceRecord, IdeaAction) |
| 40 | case scheduledRevision(WorkspaceRecord, (WorkspaceRecord) -> Void) |
| 41 | case scheduleTime(WorkspaceRecord, () -> Void) |
| 42 | case publication(WorkspaceRecord, Date?, Bool, (WorkspaceRecord) -> Void) |
| 43 | case newsletterSend(WorkspaceRecord, Bool, (WorkspaceRecord) -> Void) |
| 44 | } |
| 45 | |
| 46 | @Bindable var workspace: Workspace |
| 47 | @Environment(\.colorScheme) private var systemScheme |
| 48 | @Environment(\.scenePhase) private var scenePhase |
| 49 | @AppStorage(InkspringReview.activityKey) private var completedWriting = 0 |
| 50 | @AppStorage("studioChatAgent") private var localAgent = StudioChatAgent.codex |
| 51 | @State private var page: WorkspacePage = .workspace |
| 52 | @State private var editor: EditorRoute? |
| 53 | @State private var postBeingEdited: WorkspaceRecord? |
| 54 | @State private var ideaDraftNotice: (message: String, draftID: String)? |
| 55 | @State private var newsletterIdea: WorkspaceRecord? |
| 56 | @State private var newsletterDraft: WorkspaceRecord? |
| 57 | @State private var openingXPostID: String? |
| 58 | @State private var returnedDocumentID: String? |
| 59 | @State private var newsletterBackPage: WorkspacePage? |
| 60 | @State private var saveNewsletterBeforeLeaving: (() -> Bool)? |
| 61 | @State private var studioDraft: WorkspaceRecord? |
| 62 | @State private var scheduleFocus: String? |
| 63 | @State private var scheduleTab = ScheduleListing.Section.scheduled |
| 64 | @State private var pendingNavigation: (() -> Void)? |
| 65 | @State private var studioDirty = false |
| 66 | @State private var showsSidebar = true |
| 67 | @State private var previewExpanded = false |
| 68 | @State private var showsAgentChat = false |
| 69 | @State private var showsOnDeviceAssistant = false |
| 70 | @State private var agentChat = StudioAgentChat() |
| 71 | @State private var settingsSection = "Appearance" |
| 72 | @State private var librarySearchRequest = 0 |
| 73 | @State private var showsSupportReminder = false |
| 74 | @AppStorage(AgentGuideInvitationSchedule.dismissedKey) private var dismissedAgentInvitation = false |
| 75 | @AppStorage(AgentGuideInvitationSchedule.snoozedUntilKey) private var agentInvitationSnoozedUntil = 0.0 |
| 76 | @State private var showsConnectionGuide = false |
| 77 | |
| 78 | private var theme: StudioTheme { StudioTheme(preference: workspace.settings[StudioTheme.preferenceKey]) } |
| 79 | private var palette: StudioPalette { StudioPalette(theme: theme.resolve(for: systemScheme)) } |
| 80 | private var isEditingNewsletter: Bool { newsletterDraft != nil } |
| 81 | private var selectedPage: WorkspacePage { page == .schedule && scheduleTab == .history ? .published : page } |
| 82 | private var showsEditorPage: Bool { |
| 83 | if case .newsletterSend = editor { return false } |
| 84 | return editor != nil |
| 85 | } |
| 86 | |
| 87 | private var canShowSupportReminder: Bool { |
| 88 | scenePhase == .active && !DailyBackup.usesTestWorkspace && |
| 89 | completedWriting >= InkspringReview.milestone && |
| 90 | workspace.startupError == nil && !workspace.substackBusy && |
| 91 | [.workspace, .library, .ideas].contains(page) && |
| 92 | editor == nil && postBeingEdited == nil && !isEditingNewsletter && !studioDirty && !previewExpanded && !showsAgentChat && |
| 93 | pendingNavigation == nil && workspace.error == nil && workspace.scheduleReminderDraftID == nil |
| 94 | } |
| 95 | |
| 96 | var body: some View { |
| 97 | Group { |
| 98 | if let message = workspace.startupError { |
| 99 | ContentUnavailableView("Couldn’t open your studio", systemImage: "exclamationmark.triangle", |
| 100 | description: Text(message)) |
| 101 | } else { |
| 102 | HStack(spacing: 0) { |
| 103 | if showsSidebar && !previewExpanded && !showsEditorPage { |
| 104 | sidebar.frame(width: 244).disabled(editor != nil) |
| 105 | StudioRule(axis: .vertical) |
| 106 | } |
| 107 | VStack(spacing: 0) { |
| 108 | if !previewExpanded && !showsEditorPage { workspaceBar.disabled(editor != nil) } |
| 109 | if page == .workspace && editor == nil && !workspace.agentAccessEnabled, |
| 110 | AgentGuideInvitationSchedule.isVisible(dismissed: dismissedAgentInvitation, |
| 111 | snoozedUntil: agentInvitationSnoozedUntil) { |
| 112 | AgentGuideInvitation { |
| 113 | dismissedAgentInvitation = true |
| 114 | showsConnectionGuide = true |
| 115 | } later: { |
| 116 | agentInvitationSnoozedUntil = AgentGuideInvitationSchedule.later() |
| 117 | } dismissForever: { dismissedAgentInvitation = true } |
| 118 | } |
| 119 | ZStack { |
| 120 | content |
| 121 | .opacity(editor == nil ? 1 : 0) |
| 122 | .disabled(editor != nil) |
| 123 | .accessibilityHidden(editor != nil) |
| 124 | if let editor { editorPage(editor) } |
| 125 | } |
| 126 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | .background(palette.canvas) |
| 132 | .studioAppearance(palette) |
| 133 | .preferredColorScheme(theme == .system ? nil : palette.colorScheme) |
| 134 | .modifier(InkspringRatingPrompt(isIdle: [.workspace, .library, .ideas].contains(page) |
| 135 | && editor == nil && postBeingEdited == nil && !isEditingNewsletter |
| 136 | && pendingNavigation == nil && workspace.error == nil)) |
| 137 | .toolbar { |
| 138 | if #available(macOS 26, *) { |
| 139 | ToolbarItem(placement: .navigation) { leadingToolbar } |
| 140 | .sharedBackgroundVisibility(.hidden) |
| 141 | } else { |
| 142 | ToolbarItem(placement: .navigation) { leadingToolbar } |
| 143 | } |
| 144 | if previewExpanded && editor == nil { |
| 145 | ToolbarItem(placement: .primaryAction) { |
| 146 | creationActions |
| 147 | } |
| 148 | } |
| 149 | if editor == nil { |
| 150 | if #available(macOS 26, *) { |
| 151 | ToolbarSpacer(.flexible, placement: .primaryAction) |
| 152 | ToolbarItem(placement: .primaryAction) { quickControls } |
| 153 | .sharedBackgroundVisibility(.hidden) |
| 154 | } else { |
| 155 | ToolbarItem(placement: .primaryAction) { quickControls } |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | .onChange(of: page) { _, _ in setPreviewExpanded(false) } |
| 160 | .task(id: workspace.agentAccessEnabled) { |
| 161 | if workspace.agentAccessEnabled { _ = try? await workspace.verifyAgentConnection() } |
| 162 | } |
| 163 | .onChange(of: workspace.agentConnectionVerified) { |
| 164 | if !workspace.agentConnectionVerified { showsAgentChat = false } |
| 165 | } |
| 166 | .task(id: canShowSupportReminder) { |
| 167 | guard canShowSupportReminder else { return } |
| 168 | // Let existing sheets and the App Store review prompt take precedence. |
| 169 | do { try await Task.sleep(for: .seconds(8)) } catch { return } |
| 170 | guard canShowSupportReminder, NSApp.isActive, |
| 171 | let window = NSApp.keyWindow, !window.isSheet, window.attachedSheet == nil, |
| 172 | InkspringSupportReminder.claim() else { return } |
| 173 | showsSupportReminder = true |
| 174 | } |
| 175 | .sheet(isPresented: $showsConnectionGuide) { |
| 176 | AgentConnectionGuide(workspace: workspace).studioAppearance(palette) |
| 177 | } |
| 178 | .sheet(isPresented: $showsSupportReminder) { |
| 179 | InkspringSupportSheet(isReminder: true) |
| 180 | .studioAppearance(palette) |
| 181 | } |
| 182 | .onChange(of: workspace.projectID) { _, _ in |
| 183 | setPreviewExpanded(false) |
| 184 | agentChat = StudioAgentChat() |
| 185 | } |
| 186 | .onChange(of: workspace.scheduleReminderDraftID, initial: true) { _, id in |
| 187 | if id != nil { openScheduleReminder() } |
| 188 | } |
| 189 | .onChange(of: editor == nil) { _, isClosed in |
| 190 | if isClosed { openScheduleReminder() } |
| 191 | } |
| 192 | .sheet(isPresented: $showsAgentChat) { |
| 193 | StudioAgentChatView(workspace: workspace, chat: agentChat) { |
| 194 | showsAgentChat = false |
| 195 | navigate { |
| 196 | settingsSection = "AI agents" |
| 197 | page = .settings |
| 198 | } |
| 199 | } |
| 200 | .background(palette.canvas) |
| 201 | .studioAppearance(palette) |
| 202 | } |
| 203 | .alert("Inkspring", isPresented: Binding(get: { workspace.error != nil }, set: { if !$0 { workspace.error = nil } })) { |
| 204 | Button("OK", role: .cancel) { workspace.error = nil } |
| 205 | } message: { |
| 206 | Text(workspace.error ?? "") |
| 207 | } |
| 208 | .confirmationDialog("Keep your latest changes?", isPresented: Binding( |
| 209 | get: { pendingNavigation != nil }, set: { if !$0 { pendingNavigation = nil } } |
| 210 | ), titleVisibility: .visible) { |
| 211 | Button("Discard changes", role: .destructive) { |
| 212 | let action = pendingNavigation |
| 213 | pendingNavigation = nil |
| 214 | studioDirty = false |
| 215 | action?() |
| 216 | } |
| 217 | Button("Keep editing", role: .cancel) { pendingNavigation = nil } |
| 218 | } message: { |
| 219 | Text("This draft has unsaved changes.") |
| 220 | } |
| 221 | .overlay(alignment: .bottomTrailing) { |
| 222 | if let result = workspace.postResultNotice { |
| 223 | HStack(spacing: 12) { |
| 224 | Label(result.message, systemImage: "checkmark.circle.fill") |
| 225 | .accessibilityAddTraits(.updatesFrequently) |
| 226 | Button("View Post") { |
| 227 | navigate { |
| 228 | workspace.postResultNotice = nil |
| 229 | scheduleFocus = result.draftID |
| 230 | page = .schedule |
| 231 | } |
| 232 | } |
| 233 | .accessibilityIdentifier("post-result.view") |
| 234 | Button("Dismiss", systemImage: "xmark") { workspace.postResultNotice = nil } |
| 235 | .labelStyle(.iconOnly) |
| 236 | .buttonStyle(StudioIconButtonStyle()) |
| 237 | } |
| 238 | .padding(12) |
| 239 | .modifier(StatusGlass()) |
| 240 | .padding(18) |
| 241 | } else if let result = ideaDraftNotice { |
| 242 | HStack(spacing: 12) { |
| 243 | Label(result.message, systemImage: "checkmark.circle.fill") |
| 244 | .accessibilityAddTraits(.updatesFrequently) |
| 245 | Button("View Post") { |
| 246 | ideaDraftNotice = nil |
| 247 | if let draft = workspace.records.first(where: { $0.id == result.draftID }) { |
| 248 | navigate { open(draft) } |
| 249 | } |
| 250 | } |
| 251 | .accessibilityIdentifier("idea.draft.viewPost") |
| 252 | Button("Dismiss", systemImage: "xmark") { ideaDraftNotice = nil } |
| 253 | .labelStyle(.iconOnly) |
| 254 | .buttonStyle(StudioIconButtonStyle()) |
| 255 | } |
| 256 | .padding(12) |
| 257 | .modifier(StatusGlass()) |
| 258 | .padding(18) |
| 259 | } else if let notice = workspace.notice { |
| 260 | Button { |
| 261 | workspace.notice = nil |
| 262 | } label: { |
| 263 | Label(notice, systemImage: "checkmark.circle.fill") |
| 264 | .padding(12) |
| 265 | .modifier(StatusGlass()) |
| 266 | } |
| 267 | .buttonStyle(.plain) |
| 268 | .padding(18) |
| 269 | .task(id: notice) { |
| 270 | try? await Task.sleep(for: .seconds(5)) |
| 271 | if !Task.isCancelled { workspace.notice = nil } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | private var sidebarToggle: some View { |
| 278 | let title = previewExpanded ? "Exit full-window preview" : showsSidebar ? "Hide sidebar" : "Show sidebar" |
| 279 | return Button(title, systemImage: "sidebar.left") { |
| 280 | if previewExpanded { setPreviewExpanded(false) } |
| 281 | else { showsSidebar.toggle() } |
| 282 | } |
| 283 | .buttonStyle(StudioIconButtonStyle()) |
| 284 | .labelStyle(.iconOnly) |
| 285 | .keyboardShortcut("s", modifiers: [.command, .control]) |
| 286 | .help(title) |
| 287 | } |
| 288 | |
| 289 | private var leadingToolbar: some View { |
| 290 | HStack(spacing: 12) { |
| 291 | if !showsEditorPage { sidebarToggle } |
| 292 | Text("Inkspring") |
| 293 | .font(InkspringTypography.interface(12).weight(.bold)) |
| 294 | .foregroundStyle(palette.text) |
| 295 | .fixedSize() |
| 296 | .accessibilityAddTraits(.isHeader) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | private var quickControls: some View { |
| 301 | HStack(spacing: 12) { |
| 302 | Button("Workspace", systemImage: "square.grid.2x2") { |
| 303 | navigate { page = .workspace; setPreviewExpanded(false) } |
| 304 | } |
| 305 | .help("Workspace") |
| 306 | Button("Search drafts", systemImage: "magnifyingglass") { |
| 307 | navigate { |
| 308 | page = .library |
| 309 | setPreviewExpanded(false) |
| 310 | librarySearchRequest += 1 |
| 311 | } |
| 312 | } |
| 313 | .disabled(workspace.project == nil) |
| 314 | .help("Search drafts") |
| 315 | .keyboardShortcut("f", modifiers: [.command, .shift]) |
| 316 | Button("Settings", systemImage: "gearshape") { |
| 317 | navigate { page = .settings } |
| 318 | } |
| 319 | .help("Settings") |
| 320 | .keyboardShortcut(",", modifiers: .command) |
| 321 | } |
| 322 | .labelStyle(.iconOnly) |
| 323 | .buttonStyle(StudioIconButtonStyle()) |
| 324 | .foregroundStyle(palette.muted) |
| 325 | } |
| 326 | |
| 327 | private var sidebar: some View { |
| 328 | VStack(alignment: .leading, spacing: 3) { |
| 329 | VStack(spacing: 8) { |
| 330 | creationActions |
| 331 | sidebarDraftButton("Reply to a post", symbol: "arrowshape.turn.up.left") { navigate { newDraft(reply: true) } } |
| 332 | } |
| 333 | .padding(.horizontal, 6) |
| 334 | .padding(.bottom, 15) |
| 335 | ForEach(WorkspacePage.allCases.filter { $0 != .about && $0 != .settings }) { item in |
| 336 | navButton(item) |
| 337 | } |
| 338 | HStack { |
| 339 | Text("Projects").font(InkspringTypography.interface(12)).foregroundStyle(palette.muted) |
| 340 | Spacer() |
| 341 | Button { navigate { add("project") } } label: { Image(systemName: "plus") } |
| 342 | .buttonStyle(StudioIconButtonStyle()) |
| 343 | .accessibilityLabel("Create a project") |
| 344 | .help("New project") |
| 345 | } |
| 346 | .padding(.horizontal, 12) |
| 347 | .padding(.top, 16) |
| 348 | .padding(.bottom, 4) |
| 349 | StudioScrollView(track: palette.sidebar) { |
| 350 | VStack(alignment: .leading, spacing: 2) { |
| 351 | ForEach(workspace.projects) { project in |
| 352 | Button { |
| 353 | navigate { |
| 354 | workspace.selectProject(project.id) |
| 355 | studioDraft = nil |
| 356 | page = .workspace |
| 357 | } |
| 358 | } label: { |
| 359 | HStack(spacing: 10) { |
| 360 | ProjectMark(project: project, size: 12) |
| 361 | Text(project.title).lineLimit(1) |
| 362 | Spacer() |
| 363 | if project.fields["sample"] as? Bool == true { |
| 364 | Text("Sample").font(.caption2).foregroundStyle(.secondary) |
| 365 | } |
| 366 | } |
| 367 | .padding(.horizontal, 12) |
| 368 | .frame(minHeight: 32) |
| 369 | } |
| 370 | .foregroundStyle(project.id == workspace.projectID ? palette.text : palette.muted) |
| 371 | .buttonStyle(StudioRowStyle(selected: project.id == workspace.projectID)) |
| 372 | .accessibilityAddTraits(project.id == workspace.projectID ? .isSelected : []) |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | .frame(minHeight: 32, maxHeight: .infinity) |
| 377 | StudioRule().padding(.vertical, 6) |
| 378 | navButton(.about) |
| 379 | navButton(.settings).keyboardShortcut(",", modifiers: .command) |
| 380 | } |
| 381 | .padding(.horizontal, 17) |
| 382 | .padding(.vertical, 16) |
| 383 | .background(palette.sidebar) |
| 384 | } |
| 385 | |
| 386 | private func sidebarDraftButton(_ title: String, symbol: String, prominent: Bool = false, |
| 387 | action: @escaping () -> Void) -> some View { |
| 388 | Button(action: action) { |
| 389 | HStack(spacing: 9) { |
| 390 | Image(systemName: symbol) |
| 391 | .frame(width: 16) |
| 392 | .accessibilityHidden(true) |
| 393 | Text(title) |
| 394 | } |
| 395 | } |
| 396 | .buttonStyle(StudioActionStyle(prominent: prominent, fillsWidth: true)) |
| 397 | } |
| 398 | |
| 399 | private func navButton(_ item: WorkspacePage) -> some View { |
| 400 | Button { |
| 401 | if selectedPage != item || isEditingNewsletter || showsOnDeviceAssistant { |
| 402 | navigate { |
| 403 | if item == .studio, studioDraft == nil { startIdea() } |
| 404 | else if item == .schedule || item == .published { |
| 405 | scheduleTab = item == .published ? .history : .scheduled |
| 406 | page = .schedule |
| 407 | } |
| 408 | else { page = item } |
| 409 | } |
| 410 | } |
| 411 | } label: { |
| 412 | HStack(spacing: 11) { |
| 413 | Image(systemName: item.icon).frame(width: 18) |
| 414 | .foregroundStyle(palette.iconAccent) |
| 415 | Text(item.rawValue) |
| 416 | Spacer() |
| 417 | if let count = count(for: item), count > 0 { |
| 418 | Text(count.formatted()).font(InkspringTypography.interface(11).monospacedDigit()) |
| 419 | .padding(.horizontal, 5) |
| 420 | .padding(.vertical, 2) |
| 421 | .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(palette.line)) |
| 422 | } |
| 423 | } |
| 424 | .padding(.horizontal, 11) |
| 425 | .padding(.vertical, 7) |
| 426 | .frame(minHeight: 32) |
| 427 | .foregroundStyle(selectedPage == item ? palette.text : palette.muted) |
| 428 | } |
| 429 | .buttonStyle(StudioRowStyle(selected: selectedPage == item, indicator: true)) |
| 430 | .accessibilityAddTraits(selectedPage == item ? .isSelected : []) |
| 431 | } |
| 432 | |
| 433 | private func count(for item: WorkspacePage) -> Int? { |
| 434 | switch item { |
| 435 | case .ideas: workspace.ideas.filter { $0["status"] == "draft" }.count |
| 436 | case .schedule: workspace.records.filter { ScheduleListing.section(for: $0) == .scheduled }.count |
| 437 | case .library: workspace.workspaceDrafts.count |
| 438 | case .trash: workspace.trashedRecords.count |
| 439 | case .replies: workspace.records.filter { $0.kind == "reply-inbox" && $0["status"] == "unread" }.count |
| 440 | default: nil |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | private var workspaceTitle: String { |
| 445 | if [.settings, .connections, .analytics, .about, .schedule].contains(page) { return "Your studio" } |
| 446 | return workspace.project?.title ?? "Your workspace" |
| 447 | } |
| 448 | |
| 449 | private var workspaceBar: some View { |
| 450 | HStack(spacing: 9) { |
| 451 | Text(workspaceTitle).fontWeight(.medium).foregroundStyle(palette.text) |
| 452 | Image(systemName: "chevron.right").font(.system(size: 8, weight: .semibold)) |
| 453 | Text(selectedPage.rawValue) |
| 454 | if let newsletterDraft, let type = WorkspaceDraftType(record: newsletterDraft) { |
| 455 | Image(systemName: "chevron.right").font(.system(size: 8, weight: .semibold)) |
| 456 | Text(type.name) |
| 457 | } |
| 458 | Spacer() |
| 459 | if !showsSidebar { |
| 460 | creationActions |
| 461 | } |
| 462 | Button("Ask Inkspring", systemImage: "sparkles") { navigate { showsOnDeviceAssistant = true } } |
| 463 | if workspace.agentConnectionVerified, localAgent.executable != nil { |
| 464 | Button("Ask my agent", systemImage: "bubble.left.and.text.bubble.right") { showsAgentChat = true } |
| 465 | .disabled(workspace.project == nil) |
| 466 | .foregroundStyle(palette.text) |
| 467 | .keyboardShortcut("k", modifiers: [.command, .shift]) |
| 468 | } |
| 469 | } |
| 470 | .font(InkspringTypography.interface(12)) |
| 471 | .foregroundStyle(palette.muted) |
| 472 | .lineLimit(1) |
| 473 | .frame(height: 47) |
| 474 | .padding(.horizontal, 36) |
| 475 | .background(palette.canvas) |
| 476 | .overlay(alignment: .bottom) { StudioRule() } |
| 477 | } |
| 478 | |
| 479 | @ViewBuilder private var content: some View { |
| 480 | if showsOnDeviceAssistant { |
| 481 | InkspringAssistantChat(workspaceID: workspace.directory?.path ?? "workspace", items: { workspace.assistantContents }, |
| 482 | execute: workspace.executeAssistant, open: { id in |
| 483 | guard let item = workspace.records.first(where: { $0.id == id }) else { return } |
| 484 | showsOnDeviceAssistant = false |
| 485 | if item.kind == "project" { workspace.selectProject(item.id) } |
| 486 | else { workspace.selectProject(item.projectID); open(item) } |
| 487 | }, back: { showsOnDeviceAssistant = false }, readPlan: { id in |
| 488 | workspace.records.first { $0.id == id && ["draft", "idea", "newsletter"].contains($0.kind) }?["planMarkdown"] |
| 489 | }, applyPlan: { id, text, base in |
| 490 | let saved = try workspace.savePlan(itemID: id, markdown: text, base: base) |
| 491 | return .init(message: "Plan saved on this Mac for \(saved.referenceID ?? saved.id).", itemID: id) |
| 492 | }, loadHistory: { |
| 493 | (workspace.settings["onDeviceAssistantHistory"] as? String).flatMap { Data(base64Encoded: $0) } |
| 494 | }, saveHistory: { data in try workspace.set("onDeviceAssistantHistory", to: data.base64EncodedString()) }) |
| 495 | } else { pageContent } |
| 496 | } |
| 497 | |
| 498 | @ViewBuilder private var pageContent: some View { |
| 499 | switch page { |
| 500 | case .workspace, .library: |
| 501 | ZStack { |
| 502 | PostBrowser(workspace: workspace, library: page == .library, edit: editPost, openInStudio: open, |
| 503 | openArticle: openXPostArticle, |
| 504 | postNow: { reviewPublication($0, at: nil) { _ in } }, |
| 505 | returnedDocumentID: returnedDocumentID, postBeingEdited: postBeingEdited, back: { navigate() }, finishedEditing: { |
| 506 | postBeingEdited = nil |
| 507 | studioDirty = false |
| 508 | }, editDirtyChanged: { studioDirty = $0 }, selectPost: navigate, |
| 509 | showSchedule: showSchedule, |
| 510 | editProject: { open(workspace.project ?? .new("project")) }, |
| 511 | expanded: previewExpanded, |
| 512 | searchRequest: page == .library ? librarySearchRequest : 0, |
| 513 | togglePreview: { setPreviewExpanded(!previewExpanded) }) |
| 514 | .id("\(workspace.projectID)-\(page.rawValue)") |
| 515 | .opacity(isEditingNewsletter ? 0 : 1) |
| 516 | .disabled(isEditingNewsletter) |
| 517 | .accessibilityHidden(isEditingNewsletter) |
| 518 | if let newsletterDraft { |
| 519 | RecordEditor(record: newsletterDraft, workspace: workspace, newsletterIdea: newsletterIdea, |
| 520 | closeNewsletter: backFromNewsletter, |
| 521 | newsletterDirtyChanged: { studioDirty = $0 }, |
| 522 | newsletterSaveBeforeLeaving: { saveNewsletterBeforeLeaving = $0 }, |
| 523 | reviewNewsletter: reviewNewsletter, |
| 524 | saved: { _ in }) |
| 525 | .id(newsletterDraft.id) |
| 526 | } |
| 527 | } |
| 528 | case .ideas: |
| 529 | IdeaQueueView(workspace: workspace, add: { add("idea") }, edit: open, openDraft: open, |
| 530 | openNewsletter: draftNewsletter, showAction: { editor = .ideaAction($0, $1) }) |
| 531 | .id(workspace.projectID) |
| 532 | case .research: |
| 533 | ResearchView(workspace: workspace, add: { add("source") }, edit: open, |
| 534 | editProject: { if let project = workspace.project { open(project) } }, openDraft: open, |
| 535 | openSettings: { section in |
| 536 | navigate { settingsSection = section; page = .settings } |
| 537 | }, openConnections: { navigate { page = .connections } }) |
| 538 | .id(workspace.projectID) |
| 539 | case .schedule, .published: |
| 540 | ScheduleView(workspace: workspace, open: open, focusDraftID: $scheduleFocus, tab: $scheduleTab, |
| 541 | revise: { editor = .scheduledRevision($0, $1) }, reviewPublication: reviewPublication, |
| 542 | chooseTime: { editor = .scheduleTime($0, $1) }, reviewNewsletter: reviewNewsletter) |
| 543 | case .replies: |
| 544 | RepliesView(workspace: workspace, openDraft: draftReply) |
| 545 | case .analytics: |
| 546 | AnalyticsView(workspace: workspace, openConnections: { page = .connections }) |
| 547 | case .studio: |
| 548 | if let studioDraft { |
| 549 | DraftStudio(initial: studioDraft, workspace: workspace, onDirty: { studioDirty = $0 }, |
| 550 | showSchedule: { draft in |
| 551 | studioDirty = false |
| 552 | showSchedule(draft) |
| 553 | }, reviewPublication: reviewPublication, isActive: editor == nil, |
| 554 | openArticle: openXPostArticle) |
| 555 | .id(studioDraft.id) |
| 556 | } |
| 557 | case .settings: |
| 558 | WorkspaceSettings(workspace: workspace, initialSection: settingsSection) |
| 559 | .id(settingsSection) |
| 560 | case .connections: |
| 561 | WorkspaceConnections(workspace: workspace) |
| 562 | case .trash: |
| 563 | WorkspaceTrash(workspace: workspace) |
| 564 | case .about: |
| 565 | AboutInkspring() |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | @ViewBuilder private func editorPage(_ route: EditorRoute) -> some View { |
| 570 | switch route { |
| 571 | case .record(let record): |
| 572 | RecordEditor(record: record, workspace: workspace, closeRecord: closeEditor) { saved in |
| 573 | if saved.kind == "project" { |
| 574 | editor = nil |
| 575 | workspace.selectProject(saved.id) |
| 576 | page = .workspace |
| 577 | } else if saved.kind == "idea" { |
| 578 | editor = .savedIdea(saved) |
| 579 | } else { |
| 580 | editor = nil |
| 581 | } |
| 582 | } |
| 583 | .id(record.id) |
| 584 | case .savedIdea(let idea): |
| 585 | let current = workspace.records.first { $0.id == idea.id } ?? idea |
| 586 | MacSavedIdeaPage(idea: current, workspace: workspace, close: closeEditor, |
| 587 | edit: { editor = .record(current) }, |
| 588 | draft: { editor = .ideaAction(current, .draft) }, |
| 589 | media: { createMediaDraft($0, from: current) }, |
| 590 | image: { editor = .ideaAction($0, .image) }) |
| 591 | .id(idea.id) |
| 592 | case .quickX: |
| 593 | MacQuickXPage(workspace: workspace, close: closeEditor) { text in |
| 594 | var post = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 595 | post["platform"] = "x" |
| 596 | post["format"] = "post" |
| 597 | post["content"] = text |
| 598 | editor = .publication(post, nil, true, { _ in }) |
| 599 | } |
| 600 | case .ideaAction(let idea, let action): |
| 601 | IdeaActionPage(idea: idea, action: action, workspace: workspace, close: closeEditor) { drafts in |
| 602 | if let draft = drafts.first(where: { $0.kind == "draft" && $0["platform"] == "x" }) ?? drafts.first { |
| 603 | let noun = drafts.count == 1 ? "draft" : "drafts" |
| 604 | ideaDraftNotice = ("Created \(drafts.count) \(noun)", draft.id) |
| 605 | } |
| 606 | } |
| 607 | .id(idea.id) |
| 608 | case .scheduledRevision(let draft, let saved): |
| 609 | ScheduledDraftRevision(draft: draft, workspace: workspace, saved: saved, close: closeEditor) |
| 610 | .id(draft.id) |
| 611 | case .scheduleTime(let draft, let scheduled): |
| 612 | ScheduleTimePage(draft: draft, workspace: workspace, close: closeEditor, scheduled: scheduled, |
| 613 | reviewPublication: reviewPublication) |
| 614 | .id(draft.id) |
| 615 | case .publication(let draft, let slot, let quickX, let completed): |
| 616 | PublicationReview(draft: draft, workspace: workspace, scheduleAt: slot, quickX: quickX, completed: completed, close: closeEditor) |
| 617 | .id(draft.id) |
| 618 | case .newsletterSend(let draft, let scheduling, let completed): |
| 619 | NewsletterSendPage(record: draft, workspace: workspace, scheduling: scheduling, close: closeEditor, |
| 620 | completed: completed) |
| 621 | .id(draft.id) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | private func closeEditor() { editor = nil } |
| 626 | |
| 627 | private func openScheduleReminder() { |
| 628 | guard editor == nil, let id = workspace.scheduleReminderDraftID else { return } |
| 629 | workspace.scheduleReminderDraftID = nil |
| 630 | navigate { |
| 631 | scheduleFocus = id |
| 632 | page = .schedule |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | private func reviewPublication(_ draft: WorkspaceRecord, at date: Date?, |
| 637 | completed: @escaping (WorkspaceRecord) -> Void) { |
| 638 | editor = .publication(draft, date, false, completed) |
| 639 | } |
| 640 | |
| 641 | private func reviewNewsletter(_ draft: WorkspaceRecord, scheduling: Bool, |
| 642 | completed: @escaping (WorkspaceRecord) -> Void) { |
| 643 | editor = .newsletterSend(draft, scheduling, completed) |
| 644 | } |
| 645 | |
| 646 | private func backFromNewsletter() { |
| 647 | let destination = newsletterBackPage ?? .workspace |
| 648 | let documentID = openingXPostID ?? newsletterDraft?.id |
| 649 | let openingPost = openingXPostID.flatMap { id in workspace.drafts.first { $0.id == id } } |
| 650 | navigate { |
| 651 | returnedDocumentID = documentID |
| 652 | if destination == .studio, let openingPost { studioDraft = openingPost } |
| 653 | page = destination |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | private func editPost(_ record: WorkspaceRecord) { |
| 658 | guard record.id != postBeingEdited?.id else { return } |
| 659 | navigate { |
| 660 | if record.kind == "draft" { |
| 661 | setPreviewExpanded(false) |
| 662 | postBeingEdited = record |
| 663 | } else { |
| 664 | open(record) |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | private func add(_ kind: String) { |
| 670 | if kind == "project" || workspace.project == nil { |
| 671 | open(.new("project")) |
| 672 | return |
| 673 | } |
| 674 | open(.new(kind, projectID: workspace.projectID)) |
| 675 | } |
| 676 | |
| 677 | private var creationActions: some View { |
| 678 | HStack(spacing: 10) { |
| 679 | StudioNewIdeaButton(action: startIdea).keyboardShortcut("n") |
| 680 | Button { |
| 681 | navigate { |
| 682 | guard workspace.project != nil else { add("project"); return } |
| 683 | editor = .quickX |
| 684 | } |
| 685 | } label: { |
| 686 | StudioPlatformLabel(name: "x", title: "Quick X post") |
| 687 | } |
| 688 | .buttonStyle(StudioActionStyle()) |
| 689 | .accessibilityIdentifier("quickX.open") |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | private func startIdea() { |
| 694 | navigate { add("idea") } |
| 695 | } |
| 696 | |
| 697 | private func createMediaDraft(_ platform: String, from idea: WorkspaceRecord) { |
| 698 | var draft = WorkspaceRecord.new("draft", projectID: idea.projectID) |
| 699 | draft["ideaId"] = idea.id |
| 700 | draft["platform"] = platform |
| 701 | draft["format"] = platform == "tiktok" ? "video" : "image" |
| 702 | editor = nil |
| 703 | open(draft) |
| 704 | } |
| 705 | |
| 706 | private func newDraft(reply: Bool) { |
| 707 | guard let project = workspace.project else { add("project"); return } |
| 708 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 709 | if reply { draft["format"] = "reply" } |
| 710 | open(draft) |
| 711 | } |
| 712 | |
| 713 | private func openXPostArticle(_ article: WorkspaceRecord, from post: WorkspaceRecord) { |
| 714 | if article.isPublishedContent { |
| 715 | open(article) |
| 716 | return |
| 717 | } |
| 718 | navigate { |
| 719 | open(article) |
| 720 | openingXPostID = post.id |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | private func draftReply(_ item: WorkspaceRecord) { |
| 725 | guard workspace.project != nil else { add("project"); return } |
| 726 | workspace.perform { |
| 727 | let draft = try workspace.makeReplyDraft(item.id, projectID: workspace.projectID) |
| 728 | if draft.projectID != workspace.projectID { workspace.selectProject(draft.projectID) } |
| 729 | open(draft) |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | private func showSchedule(_ draft: WorkspaceRecord) { |
| 734 | scheduleFocus = draft.id |
| 735 | page = .schedule |
| 736 | } |
| 737 | |
| 738 | private func setPreviewExpanded(_ expanded: Bool) { |
| 739 | previewExpanded = expanded |
| 740 | } |
| 741 | |
| 742 | private func draftNewsletter(from idea: WorkspaceRecord) { |
| 743 | var draft = WorkspaceRecord.new("newsletter", projectID: idea.projectID) |
| 744 | draft["title"] = String(idea["topic"].prefix(300)) |
| 745 | newsletterIdea = idea |
| 746 | open(draft) |
| 747 | } |
| 748 | |
| 749 | private func open(_ record: WorkspaceRecord) { |
| 750 | if record.isPublishedContent { |
| 751 | if let url = PublishedPostFeed.entries(in: workspace.records, projectID: record.projectID) |
| 752 | .first(where: { $0.id == record.id })?.links.first { |
| 753 | NSWorkspace.shared.open(url) |
| 754 | } else { |
| 755 | scheduleTab = .history |
| 756 | page = .schedule |
| 757 | } |
| 758 | return |
| 759 | } |
| 760 | if ["draft", "newsletter", "script", "article"].contains(record.kind), record.projectID != workspace.projectID, |
| 761 | workspace.projects.contains(where: { $0.id == record.projectID }) { |
| 762 | workspace.selectProject(record.projectID) |
| 763 | } |
| 764 | if record.kind == "draft" { |
| 765 | studioDraft = record |
| 766 | page = .studio |
| 767 | } else if record.isLongForm { |
| 768 | returnedDocumentID = nil |
| 769 | newsletterBackPage = page |
| 770 | newsletterDraft = record |
| 771 | setPreviewExpanded(false) |
| 772 | if page != .library { page = .workspace } |
| 773 | } else { |
| 774 | editor = .record(record) |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | private func navigate(_ action: @escaping () -> Void = {}) { |
| 779 | let leave = { |
| 780 | showsOnDeviceAssistant = false |
| 781 | postBeingEdited = nil |
| 782 | if isEditingNewsletter { |
| 783 | newsletterDraft = nil |
| 784 | openingXPostID = nil |
| 785 | newsletterIdea = nil |
| 786 | newsletterBackPage = nil |
| 787 | } |
| 788 | action() |
| 789 | } |
| 790 | if isEditingNewsletter, let saveNewsletterBeforeLeaving { |
| 791 | guard saveNewsletterBeforeLeaving() else { return } |
| 792 | studioDirty = false |
| 793 | leave() |
| 794 | } else if studioDirty { |
| 795 | pendingNavigation = leave |
| 796 | } else { |
| 797 | leave() |
| 798 | } |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | struct PageHeading: View { |
| 803 | let title: String |
| 804 | var subtitle: String? = nil |
| 805 | var titleSize: CGFloat = 42 |
| 806 | |
| 807 | var body: some View { |
| 808 | VStack(alignment: .leading, spacing: 7) { |
| 809 | Text(title) |
| 810 | .font(InkspringTypography.editorial(titleSize, relativeTo: .largeTitle)) |
| 811 | .tracking(-titleSize / 35) |
| 812 | .accessibilityAddTraits(.isHeader) |
| 813 | if let subtitle { |
| 814 | Text(subtitle) |
| 815 | .font(InkspringTypography.interface(14)) |
| 816 | .foregroundStyle(.secondary) |
| 817 | .fixedSize(horizontal: false, vertical: true) |
| 818 | } |
| 819 | } |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | struct ProjectMark: View { |
| 824 | @Environment(\.studioPalette) private var palette |
| 825 | let project: WorkspaceRecord |
| 826 | var size: CGFloat |
| 827 | |
| 828 | var body: some View { |
| 829 | let symbols = ["folder": "folder.fill", "studio": "paintpalette.fill", "ink": "drop.fill", "book": "book.fill", |
| 830 | "video": "video.fill", "idea": "lightbulb.fill", "flask": "flask.fill", "code": "chevron.left.forwardslash.chevron.right", |
| 831 | "globe": "globe", "mic": "mic.fill", "waveform": "waveform"] |
| 832 | Image(systemName: symbols[project["icon"]] ?? "circle.fill") |
| 833 | .font(.system(size: size)) |
| 834 | .foregroundStyle(palette.project(project["color"])) |
| 835 | .frame(width: size + 4, height: size + 4) |
| 836 | .accessibilityHidden(true) |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | struct RecordCard: View { |
| 841 | let record: WorkspaceRecord |
| 842 | |
| 843 | var body: some View { |
| 844 | let platform = record.kind == "newsletter" ? "substack" : record["platform"] |
| 845 | VStack(alignment: .leading, spacing: 9) { |
| 846 | if !platform.isEmpty { |
| 847 | StudioPlatformLabel(name: platform, title: record.kind == "article" ? WorkspaceDraftType(record: record)?.name ?? "X article" : platformName(platform)) |
| 848 | .font(.caption) |
| 849 | .foregroundStyle(.secondary) |
| 850 | } |
| 851 | Text(record.title).font(.headline) |
| 852 | if !record.body.isEmpty { |
| 853 | Text(preview) |
| 854 | .font(InkspringTypography.interface(17)) |
| 855 | .lineLimit(5) |
| 856 | .foregroundStyle(.secondary) |
| 857 | } |
| 858 | if record.fields["sample"] as? Bool == true { |
| 859 | Text("Sample").font(.caption).foregroundStyle(.secondary) |
| 860 | } |
| 861 | } |
| 862 | .frame(maxWidth: .infinity, alignment: .leading) |
| 863 | .padding(16) |
| 864 | .studioSurface() |
| 865 | } |
| 866 | |
| 867 | private var preview: AttributedString { |
| 868 | guard record.isLongForm, |
| 869 | let markdown = try? AttributedString(markdown: record.body, |
| 870 | options: .init(failurePolicy: .returnPartiallyParsedIfPossible)) else { |
| 871 | return AttributedString(record.body) |
| 872 | } |
| 873 | var result = AttributedString() |
| 874 | var previousBlock: Int? |
| 875 | for run in markdown.runs { |
| 876 | let block = run.presentationIntent?.components.first?.identity |
| 877 | if !result.characters.isEmpty, block != previousBlock { |
| 878 | result.append(AttributedString("\n")) |
| 879 | } |
| 880 | var text = AttributedString(markdown[run.range]) |
| 881 | text.presentationIntent = nil |
| 882 | // Keep the card's click action instead of opening a preview link. |
| 883 | if text.link != nil { text.underlineStyle = .single } |
| 884 | text.link = nil |
| 885 | result.append(text) |
| 886 | previousBlock = block |
| 887 | } |
| 888 | return result |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | func platformName(_ value: String) -> String { |
| 893 | ["youtube": "YouTube", "x": "X", "linkedin": "LinkedIn", "instagram": "Instagram", "reddit": "Reddit", "tiktok": "TikTok", |
| 894 | "x-article": "X article", "linkedin-article": "LinkedIn article", "substack": "Substack"][value] |
| 895 | ?? value.capitalized |
| 896 | } |
| 897 | |
| 898 | enum WorkspaceDraftType: String, CaseIterable { |
| 899 | case post = "draft", newsletter, article, script |
| 900 | case linkedInArticle = "linkedin-article" |
| 901 | |
| 902 | init?(record: WorkspaceRecord) { |
| 903 | self.init(rawValue: record.isLinkedInWritingArticle ? "linkedin-article" : record.kind) |
| 904 | } |
| 905 | |
| 906 | func makeRecord(projectID: String) -> WorkspaceRecord { |
| 907 | guard self == .linkedInArticle else { return WorkspaceRecord.new(rawValue, projectID: projectID) } |
| 908 | var draft = WorkspaceRecord.new("article", projectID: projectID) |
| 909 | draft["platform"] = "linkedin" |
| 910 | draft.fields["writingOnly"] = true |
| 911 | return draft |
| 912 | } |
| 913 | |
| 914 | var name: String { |
| 915 | switch self { |
| 916 | case .post: "Social post" |
| 917 | case .newsletter: "Newsletter" |
| 918 | case .article: "X article" |
| 919 | case .linkedInArticle: "LinkedIn article" |
| 920 | case .script: "YouTube script" |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | var symbol: String { |
| 925 | switch self { |
| 926 | case .post: "text.bubble" |
| 927 | case .newsletter: "envelope" |
| 928 | case .article, .linkedInArticle: "doc.richtext" |
| 929 | case .script: "play.rectangle" |
| 930 | } |
| 931 | } |
| 932 | } |
| 933 | |
| 934 | enum PostBrowserFilter: String, CaseIterable { |
| 935 | case all = "All drafts" |
| 936 | case draft = "Draft" |
| 937 | case ideas = "Post ideas" |
| 938 | case scheduling = "Ready to schedule" |
| 939 | |
| 940 | func matches(_ record: WorkspaceRecord, platform: String?, search: String) -> Bool { |
| 941 | guard self == .ideas ? record.kind == "idea" : WorkspaceDraftType(record: record) != nil else { return false } |
| 942 | if self != .ideas, let platform, ScheduleListing.channel(of: record) != platform { return false } |
| 943 | let matchingStatus = switch self { |
| 944 | case .all: true |
| 945 | case .draft: record.isLongForm ? ["draft", "synced", "syncing"].contains(record["state"]) |
| 946 | : !["queued", "due", "posting", "posted", "skipped", "uncertain"].contains(record.scheduleStatus) |
| 947 | case .ideas: record["status"] == "draft" |
| 948 | case .scheduling: ScheduleListing.section(for: record) == .ready |
| 949 | } |
| 950 | let query = search.trimmingCharacters(in: .whitespacesAndNewlines) |
| 951 | var searchFields = [record.referenceID ?? "", record.title, record.body] |
| 952 | if self != .ideas { |
| 953 | searchFields += [record["subtitle"], WorkspaceDraftType(record: record)?.name ?? "", |
| 954 | platformName(ScheduleListing.channel(of: record))] |
| 955 | } |
| 956 | return matchingStatus && (query.isEmpty || searchFields.contains { $0.localizedCaseInsensitiveContains(query) }) |
| 957 | } |
| 958 | } |
| 959 | |
| 960 | struct PostBrowser: View { |
| 961 | private enum DraftSort: String, CaseIterable { |
| 962 | case lastUpdated = "Last updated" |
| 963 | case oldestUpdate = "Oldest update" |
| 964 | case title = "Title A–Z" |
| 965 | |
| 966 | func sorted(_ records: [WorkspaceRecord]) -> [WorkspaceRecord] { |
| 967 | if self == .title { |
| 968 | return records.map { (record: $0, title: $0.title) } |
| 969 | .sorted { lhs, rhs in |
| 970 | let order = lhs.title.localizedStandardCompare(rhs.title) |
| 971 | return order == .orderedSame ? lhs.record.id > rhs.record.id : order == .orderedAscending |
| 972 | } |
| 973 | .map(\.record) |
| 974 | } |
| 975 | return records.map { (record: $0, date: scheduleDate($0["updatedAt"])) } |
| 976 | .sorted { lhs, rhs in |
| 977 | if lhs.date == rhs.date { return lhs.record.id > rhs.record.id } |
| 978 | guard let lhsDate = lhs.date else { return false } |
| 979 | guard let rhsDate = rhs.date else { return true } |
| 980 | return self == .lastUpdated ? lhsDate > rhsDate : lhsDate < rhsDate |
| 981 | } |
| 982 | .map(\.record) |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | @Environment(\.studioPalette) private var palette |
| 987 | let workspace: Workspace |
| 988 | let library: Bool |
| 989 | let edit: (WorkspaceRecord) -> Void |
| 990 | let openInStudio: (WorkspaceRecord) -> Void |
| 991 | let openArticle: (WorkspaceRecord, WorkspaceRecord) -> Void |
| 992 | let postNow: (WorkspaceRecord) -> Void |
| 993 | let returnedDocumentID: String? |
| 994 | let postBeingEdited: WorkspaceRecord? |
| 995 | let back: () -> Void |
| 996 | let finishedEditing: () -> Void |
| 997 | let editDirtyChanged: (Bool) -> Void |
| 998 | let selectPost: (@escaping () -> Void) -> Void |
| 999 | let showSchedule: (WorkspaceRecord) -> Void |
| 1000 | let editProject: () -> Void |
| 1001 | let expanded: Bool |
| 1002 | let searchRequest: Int |
| 1003 | let togglePreview: () -> Void |
| 1004 | @State private var selection: String? |
| 1005 | @State private var type: WorkspaceDraftType? |
| 1006 | @State private var filter = PostBrowserFilter.all |
| 1007 | @State private var platform: String? |
| 1008 | @State private var search = "" |
| 1009 | @AppStorage("inkspring.mac.draftSort") private var draftSort = DraftSort.lastUpdated |
| 1010 | @FocusState private var searchFocused: Bool |
| 1011 | |
| 1012 | private var statuses: [PostBrowserFilter] { |
| 1013 | if library || type == .script || type == .article { return [.all, .draft] } |
| 1014 | return [.all, .draft, .scheduling] |
| 1015 | } |
| 1016 | |
| 1017 | private func records(for filter: PostBrowserFilter, query: String = "") -> [WorkspaceRecord] { |
| 1018 | let rows = (filter == .ideas ? workspace.ideas : workspace.workspaceDrafts).filter { |
| 1019 | (type == nil || WorkspaceDraftType(record: $0) == type) && filter.matches($0, platform: platform, search: query) |
| 1020 | } |
| 1021 | return rows |
| 1022 | } |
| 1023 | |
| 1024 | var body: some View { |
| 1025 | if workspace.project == nil { |
| 1026 | ContentUnavailableView { |
| 1027 | Label("Create a project to get started", systemImage: "folder") |
| 1028 | } actions: { |
| 1029 | Button("Create a project", systemImage: "plus", action: editProject) |
| 1030 | .modifier(PrimaryActionStyle()) |
| 1031 | } |
| 1032 | } else { |
| 1033 | reader |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | private var reader: some View { |
| 1038 | let matchingRecords = records(for: filter, query: search) |
| 1039 | let rows = draftSort.sorted(matchingRecords) |
| 1040 | let selected = rows.first { $0.id == selection } |
| 1041 | ?? rows.first |
| 1042 | return VStack(alignment: .leading, spacing: 0) { |
| 1043 | if !expanded { |
| 1044 | HStack(spacing: 12) { |
| 1045 | if !library, let project = workspace.project { |
| 1046 | HStack(alignment: .firstTextBaseline, spacing: 10) { |
| 1047 | ProjectMark(project: project, size: 17) |
| 1048 | .padding(6) |
| 1049 | .studioSurface(StudioRadius.control) |
| 1050 | .alignmentGuide(.firstTextBaseline) { dimensions in |
| 1051 | dimensions[VerticalAlignment.center] + InkspringTypography.editorialCapHeight(32) / 2 |
| 1052 | } |
| 1053 | PageHeading(title: project.title, titleSize: 32).lineLimit(2) |
| 1054 | } |
| 1055 | Button("Edit project", action: editProject) |
| 1056 | } else { |
| 1057 | PageHeading(title: "Library", titleSize: 32) |
| 1058 | } |
| 1059 | Spacer(minLength: 8) |
| 1060 | } |
| 1061 | .padding(.bottom, 18) |
| 1062 | StudioTabs(selection: Binding(get: { type }, set: { newType in |
| 1063 | selectPost { |
| 1064 | type = newType |
| 1065 | filter = .all |
| 1066 | platform = nil |
| 1067 | selection = nil |
| 1068 | } |
| 1069 | }), tabs: [nil] + WorkspaceDraftType.allCases.map(Optional.some), |
| 1070 | label: { $0.map { $0.name + "s" } ?? "All drafts" }, |
| 1071 | count: { format in |
| 1072 | if let format { return workspace.workspaceDrafts.filter { WorkspaceDraftType(record: $0) == format }.count } |
| 1073 | return workspace.workspaceDrafts.count |
| 1074 | }) |
| 1075 | } |
| 1076 | GeometryReader { geometry in |
| 1077 | HStack(spacing: 0) { |
| 1078 | if !expanded { |
| 1079 | postList(rows, selected: postBeingEdited?.id ?? selected?.id) |
| 1080 | .padding(.trailing, 16) |
| 1081 | .frame(width: min(max(210, geometry.size.width * 0.29), 330)) |
| 1082 | .frame(maxHeight: .infinity) |
| 1083 | StudioRule(axis: .vertical) |
| 1084 | } |
| 1085 | Group { |
| 1086 | if let postBeingEdited { |
| 1087 | PostInlineEditor(record: postBeingEdited, workspace: workspace, back: back, |
| 1088 | saved: finishedEditing, onDirty: editDirtyChanged, |
| 1089 | openArticle: openArticle) |
| 1090 | .id(postBeingEdited.id) |
| 1091 | } else if let selected { |
| 1092 | if selected.isLongForm, let format = WorkspaceDraftType(record: selected) { |
| 1093 | longFormPreview(selected, type: format) |
| 1094 | .id(selected.id) |
| 1095 | } else { |
| 1096 | PostPreview(record: selected, workspace: workspace, edit: edit, openInStudio: openInStudio, |
| 1097 | openArticle: openArticle, postNow: postNow, showSchedule: showSchedule, |
| 1098 | expanded: expanded, togglePreview: togglePreview) |
| 1099 | .id(selected.id) |
| 1100 | } |
| 1101 | } else { |
| 1102 | VStack { |
| 1103 | ContentUnavailableView("No matching drafts", systemImage: "doc.text") |
| 1104 | if expanded { |
| 1105 | Button("Exit full-window preview", action: togglePreview).keyboardShortcut(.cancelAction) |
| 1106 | } |
| 1107 | } |
| 1108 | } |
| 1109 | } |
| 1110 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 1111 | } |
| 1112 | } |
| 1113 | } |
| 1114 | .padding(.horizontal, expanded ? 0 : 36) |
| 1115 | .padding(.vertical, expanded ? 0 : 26) |
| 1116 | .onChange(of: returnedDocumentID) { _, id in |
| 1117 | guard let id, let record = workspace.workspaceDrafts.first(where: { $0.id == id }) else { return } |
| 1118 | if !rows.contains(where: { $0.id == id }) { |
| 1119 | type = WorkspaceDraftType(record: record) |
| 1120 | filter = .all |
| 1121 | platform = nil |
| 1122 | search = "" |
| 1123 | } |
| 1124 | selection = id |
| 1125 | } |
| 1126 | .onChange(of: postBeingEdited?.id) { _, id in |
| 1127 | if let id { selection = id } |
| 1128 | } |
| 1129 | .onChange(of: searchRequest, initial: true) { _, request in |
| 1130 | if request > 0 { |
| 1131 | Task { @MainActor in |
| 1132 | await Task.yield() |
| 1133 | searchFocused = true |
| 1134 | } |
| 1135 | } |
| 1136 | } |
| 1137 | } |
| 1138 | |
| 1139 | private func postList(_ rows: [WorkspaceRecord], selected: String?) -> some View { |
| 1140 | VStack(alignment: .leading, spacing: 10) { |
| 1141 | StudioSearchField(title: filter == .ideas ? "Search ideas" : "Search drafts", text: $search) |
| 1142 | .focused($searchFocused) |
| 1143 | .padding(.top, 16) |
| 1144 | |
| 1145 | StudioFilterMenu(title: "Filter drafts", value: filter == .all ? "All statuses" : filter.rawValue) { |
| 1146 | ForEach(statuses, id: \.self) { status in |
| 1147 | Button { |
| 1148 | selectPost { filter = status; selection = nil } |
| 1149 | } label: { |
| 1150 | if filter == status { Label(status == .all ? "All statuses" : status.rawValue, systemImage: "checkmark") } |
| 1151 | else { Text(status == .all ? "All statuses" : status.rawValue) } |
| 1152 | } |
| 1153 | } |
| 1154 | if !library && type == nil { |
| 1155 | Divider() |
| 1156 | Button("Post ideas", systemImage: "lightbulb") { |
| 1157 | selectPost { filter = .ideas; platform = nil; selection = nil } |
| 1158 | } |
| 1159 | } |
| 1160 | } |
| 1161 | HStack(spacing: 8) { |
| 1162 | if filter != .ideas && (type == nil || type == .post) { |
| 1163 | let channels = SocialPlatform.allCases.map(\.rawValue) + (type == nil ? ["substack", "youtube"] : []) |
| 1164 | StudioChoicePicker(title: "Filter by platform", selection: $platform, |
| 1165 | options: [nil] + channels.map(Optional.some), |
| 1166 | label: { $0.map(platformName) ?? "All platforms" }, |
| 1167 | icon: { $0.flatMap(PlatformMark.image) }) |
| 1168 | } |
| 1169 | StudioFilterMenu(title: "Sort drafts", value: "Sort") { |
| 1170 | Picker("Sort drafts", selection: $draftSort) { |
| 1171 | ForEach(DraftSort.allCases, id: \.self) { option in |
| 1172 | Text(option.rawValue).tag(option) |
| 1173 | } |
| 1174 | } |
| 1175 | .pickerStyle(.inline) |
| 1176 | } |
| 1177 | .accessibilityValue(draftSort.rawValue) |
| 1178 | } |
| 1179 | .padding(.bottom, 3) |
| 1180 | |
| 1181 | StudioScrollView { |
| 1182 | LazyVStack(alignment: .leading, spacing: 4) { |
| 1183 | if rows.isEmpty { |
| 1184 | Text(search.isEmpty ? "Nothing here yet." : "No matches.") |
| 1185 | .foregroundStyle(palette.muted) |
| 1186 | .padding(10) |
| 1187 | } |
| 1188 | ForEach(rows) { row in |
| 1189 | StudioRule().padding(.horizontal, 8) |
| 1190 | Button { |
| 1191 | if postBeingEdited?.id != row.id { selectPost { selection = row.id } } |
| 1192 | } label: { |
| 1193 | HStack(alignment: .top, spacing: 9) { |
| 1194 | Image(systemName: postBrowserIcon(row)) |
| 1195 | .foregroundStyle(palette.iconAccent) |
| 1196 | .frame(width: 15) |
| 1197 | .padding(.top, 2) |
| 1198 | VStack(alignment: .leading, spacing: 5) { |
| 1199 | Text(row.title).font(InkspringTypography.interface(13).weight(.medium)).lineLimit(2) |
| 1200 | Group { |
| 1201 | if row.isLongForm, let type = WorkspaceDraftType(record: row) { |
| 1202 | let status = type.name + " · " + row["state"].capitalized |
| 1203 | if type == .script { StudioPlatformLabel(name: ScheduleListing.channel(of: row), title: status) } |
| 1204 | else { Text(status) } |
| 1205 | } |
| 1206 | else if row["platform"].isEmpty { Text(postBrowserStatus(row)) } |
| 1207 | else { StudioPlatformLabel(name: row["platform"], title: postBrowserStatus(row)) } |
| 1208 | } |
| 1209 | .font(InkspringTypography.interface(11)) |
| 1210 | .foregroundStyle(palette.muted).lineLimit(2) |
| 1211 | } |
| 1212 | } |
| 1213 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1214 | .padding(.horizontal, 10) |
| 1215 | .padding(.vertical, 12) |
| 1216 | } |
| 1217 | .buttonStyle(StudioRowStyle(selected: selected == row.id, indicator: true)) |
| 1218 | .accessibilityAddTraits(selected == row.id ? .isSelected : []) |
| 1219 | .contextMenu { |
| 1220 | Button("Edit…", systemImage: "pencil") { edit(row) } |
| 1221 | .disabled(["posting", "posted"].contains(row.scheduleStatus)) |
| 1222 | Button("Copy text", systemImage: "doc.on.doc") { copy(row.body) } |
| 1223 | if !row.isLongForm { |
| 1224 | Button(row.kind == "idea" ? "Skip idea" : "Move to Trash", systemImage: "trash") { |
| 1225 | workspace.perform { try workspace.trashLibraryItem(row) } |
| 1226 | } |
| 1227 | } |
| 1228 | } |
| 1229 | } |
| 1230 | if !rows.isEmpty { StudioRule().padding(.horizontal, 8) } |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | private func longFormPreview(_ record: WorkspaceRecord, type: WorkspaceDraftType) -> some View { |
| 1237 | StudioScrollView { |
| 1238 | VStack(alignment: .leading, spacing: 14) { |
| 1239 | HStack { |
| 1240 | StudioPlatformLabel(name: ScheduleListing.channel(of: record), title: type.name) |
| 1241 | Spacer() |
| 1242 | Button(expanded ? "Exit full-window preview" : "Full-window preview", |
| 1243 | systemImage: expanded ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right", |
| 1244 | action: togglePreview) |
| 1245 | .labelStyle(.iconOnly) |
| 1246 | .buttonStyle(StudioIconButtonStyle()) |
| 1247 | .keyboardShortcut(expanded ? .cancelAction : nil) |
| 1248 | } |
| 1249 | HStack { |
| 1250 | if let reference = record.referenceID { StudioCopyReference(reference: reference) } |
| 1251 | if let updated = scheduleDate(record["updatedAt"]) { |
| 1252 | Text("Last updated \(updated.formatted(date: .abbreviated, time: .shortened))") |
| 1253 | .font(.caption).foregroundStyle(palette.muted) |
| 1254 | } |
| 1255 | } |
| 1256 | StudioRule() |
| 1257 | HStack { |
| 1258 | Button(["draft", "synced"].contains(record["state"]) ? "Edit draft" : "Open document", |
| 1259 | systemImage: "square.and.pencil") { edit(record) } |
| 1260 | Button("Copy", systemImage: "doc.on.doc") { copy(record.body) } |
| 1261 | } |
| 1262 | NewsletterPreview(title: record.title, subtitle: record["subtitle"], markdown: record.body, |
| 1263 | cover: workspace.mediaURL(record)) |
| 1264 | } |
| 1265 | .padding(24) |
| 1266 | .frame(maxWidth: 760, alignment: .leading) |
| 1267 | .frame(maxWidth: .infinity) |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | private func postBrowserStatus(_ record: WorkspaceRecord) -> String { |
| 1272 | if record.kind == "idea" { return "Post idea" } |
| 1273 | let status = switch record.scheduleStatus { |
| 1274 | case "queued": "Scheduled" |
| 1275 | case "due": "Time to post" |
| 1276 | case "posting": "Posting" |
| 1277 | case "posted": "Posted" |
| 1278 | case "skipped": "Skipped" |
| 1279 | case "uncertain": "Check publishing" |
| 1280 | default: "Draft" |
| 1281 | } |
| 1282 | let attachment = record.fields["video"] is [String: Any] ? " · Video" |
| 1283 | : record.fields["image"] is [String: Any] ? " · Image" : "" |
| 1284 | return "\(platformName(record["platform"])) · \(status)\(attachment)" |
| 1285 | } |
| 1286 | |
| 1287 | private func postBrowserIcon(_ record: WorkspaceRecord) -> String { |
| 1288 | if record.isLongForm, let type = WorkspaceDraftType(record: record) { return type.symbol } |
| 1289 | if record.fields["video"] is [String: Any] { return "play.rectangle" } |
| 1290 | if record.fields["image"] is [String: Any] { return "photo" } |
| 1291 | return record.kind == "idea" ? "sparkles" : "doc.text" |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | struct PostPreview: View { |
| 1296 | @Environment(\.studioPalette) private var palette |
| 1297 | let record: WorkspaceRecord |
| 1298 | let workspace: Workspace |
| 1299 | let edit: (WorkspaceRecord) -> Void |
| 1300 | let openInStudio: (WorkspaceRecord) -> Void |
| 1301 | let openArticle: (WorkspaceRecord, WorkspaceRecord) -> Void |
| 1302 | let postNow: (WorkspaceRecord) -> Void |
| 1303 | let showSchedule: (WorkspaceRecord) -> Void |
| 1304 | let expanded: Bool |
| 1305 | let togglePreview: () -> Void |
| 1306 | @State private var revisionRequest = "" |
| 1307 | @State private var composingRevisionRequest = false |
| 1308 | @State private var outlineID: String? |
| 1309 | |
| 1310 | var body: some View { |
| 1311 | if outlineID == record.id, let current = workspace.records.first(where: { $0.id == record.id }) { |
| 1312 | WorkspaceOutline(record: current, workspace: workspace) { outlineID = nil } |
| 1313 | } else { |
| 1314 | preview |
| 1315 | } |
| 1316 | } |
| 1317 | |
| 1318 | private var preview: some View { |
| 1319 | StudioScrollView { |
| 1320 | VStack(alignment: .leading, spacing: 20) { |
| 1321 | HStack(alignment: .top, spacing: 12) { |
| 1322 | VStack(alignment: .leading, spacing: 9) { |
| 1323 | Group { |
| 1324 | if record.kind == "idea" { Label("Post idea", systemImage: "sparkles") } |
| 1325 | else { StudioPlatformLabel(name: record["platform"], title: platformName(record["platform"])) } |
| 1326 | } |
| 1327 | .font(InkspringTypography.interface(12)) |
| 1328 | .foregroundStyle(palette.muted) |
| 1329 | Text(record.title) |
| 1330 | .font(InkspringTypography.editorial(24, relativeTo: .title2)) |
| 1331 | .lineSpacing(3) |
| 1332 | .fixedSize(horizontal: false, vertical: true) |
| 1333 | .accessibilityAddTraits(.isHeader) |
| 1334 | if let reference = record.referenceID { |
| 1335 | StudioCopyReference(reference: reference) |
| 1336 | } |
| 1337 | if record.kind == "draft", let updatedAt = scheduleDate(record["updatedAt"]) { |
| 1338 | Text("Last updated \(updatedAt.formatted(date: .abbreviated, time: .standard))") |
| 1339 | .font(.caption) |
| 1340 | .foregroundStyle(palette.muted) |
| 1341 | .accessibilityIdentifier("post.lastUpdated") |
| 1342 | } |
| 1343 | } |
| 1344 | Spacer(minLength: 5) |
| 1345 | let previewLabel = expanded ? "Exit full-window preview" : "Full-window preview" |
| 1346 | Button(previewLabel, systemImage: expanded ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right", |
| 1347 | action: togglePreview) |
| 1348 | .labelStyle(.iconOnly) |
| 1349 | .buttonStyle(StudioIconButtonStyle()) |
| 1350 | .help(previewLabel) |
| 1351 | .keyboardShortcut(expanded ? .cancelAction : nil) |
| 1352 | } |
| 1353 | StudioRule() |
| 1354 | HStack(alignment: .top, spacing: 12) { |
| 1355 | ViewThatFits(in: .horizontal) { |
| 1356 | HStack(spacing: 8) { previewActions } |
| 1357 | VStack(alignment: .leading, spacing: 8) { previewActions } |
| 1358 | } |
| 1359 | Spacer(minLength: 8) |
| 1360 | previewMoreActions |
| 1361 | } |
| 1362 | postArticleControls |
| 1363 | if record.fields["video"] is [String: Any] { |
| 1364 | attachment("Video", icon: "video", url: workspace.videoURL(record)) |
| 1365 | } |
| 1366 | if record.fields["image"] is [String: Any] { |
| 1367 | attachment("Image", icon: "photo", url: workspace.imageURL(record)) |
| 1368 | } |
| 1369 | if record.kind == "draft", ScheduleListing.section(for: record) == .ready { |
| 1370 | Button("Open in Schedule", systemImage: "calendar") { showSchedule(record) } |
| 1371 | } |
| 1372 | VStack(alignment: .leading, spacing: 12) { |
| 1373 | if let target = record.fields["replyTo"] as? [String: String], let text = target["text"], !text.isEmpty { |
| 1374 | Text(text).font(.callout).foregroundStyle(.secondary) |
| 1375 | } |
| 1376 | if !record.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { |
| 1377 | if record["platform"] == "x", ["followup", "thread"].contains(record["format"]) { |
| 1378 | let posts = XThreadText.posts(in: record.body) |
| 1379 | ForEach(posts.indices, id: \.self) { index in |
| 1380 | VStack(alignment: .leading, spacing: 8) { |
| 1381 | HStack { |
| 1382 | Label(index == 0 ? "Opening post" : "Follow-up reply \(index)", systemImage: index == 0 ? "text.bubble" : "arrow.turn.down.right") |
| 1383 | .font(.callout.weight(.semibold)).foregroundStyle(palette.iconAccent) |
| 1384 | Spacer() |
| 1385 | Button("Edit", systemImage: "pencil") { edit(record) } |
| 1386 | } |
| 1387 | let link = XReplyArticle(posts[index]) |
| 1388 | if !link.copy.isEmpty { Text(link.copy).font(InkspringTypography.interface(17)).lineSpacing(5).textSelection(.enabled) } |
| 1389 | if let ref = link.reference { |
| 1390 | if let article = workspace.records.first(where: { $0.projectID == record.projectID && $0.isXArticle && $0.referenceID == ref }) { |
| 1391 | if let url = CompanionPublication.postURL(article["articleURL"]) { |
| 1392 | StudioExternalLink("Open X article · " + article.title, destination: url) |
| 1393 | } else { |
| 1394 | Button("X article · " + article.title, systemImage: "doc.text") { edit(article) } |
| 1395 | Text("Publish the article first to include its X link.").font(.caption).foregroundStyle(palette.muted) |
| 1396 | } |
| 1397 | } else { Text("Linked X article unavailable · " + ref).font(.caption) } |
| 1398 | } |
| 1399 | } |
| 1400 | if index < posts.count - 1 { StudioRule() } |
| 1401 | } |
| 1402 | } else { |
| 1403 | Text(record.body).font(InkspringTypography.interface(17)).lineSpacing(5).textSelection(.enabled) |
| 1404 | } |
| 1405 | } |
| 1406 | } |
| 1407 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1408 | .padding(16) |
| 1409 | .studioSurface() |
| 1410 | revisionRequests |
| 1411 | } |
| 1412 | .padding(.vertical, expanded ? 34 : 22) |
| 1413 | .padding(.horizontal, expanded ? 34 : 24) |
| 1414 | .frame(maxWidth: 760, alignment: .leading) |
| 1415 | .frame(maxWidth: .infinity) |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | private var revisionRequests: some View { |
| 1420 | let current = workspace.records.first { $0.id == record.id && $0.kind == record.kind } ?? record |
| 1421 | return VStack(alignment: .leading, spacing: 12) { |
| 1422 | Text(StudioRevisionRequestCopy.heading).font(InkspringTypography.editorial(19, relativeTo: .headline)) |
| 1423 | if current.acceptsRevisionComments { |
| 1424 | if !composingRevisionRequest { |
| 1425 | Button(StudioRevisionRequestCopy.add, systemImage: "plus") { composingRevisionRequest = true } |
| 1426 | .disabled(!workspace.writingToolsAvailable) |
| 1427 | } else { |
| 1428 | HStack(alignment: .firstTextBaseline) { |
| 1429 | TextField(StudioRevisionRequestCopy.field, text: $revisionRequest, |
| 1430 | prompt: Text(current.kind == "idea" ? StudioRevisionRequestCopy.ideaExample : StudioRevisionRequestCopy.draftExample), |
| 1431 | axis: .vertical) |
| 1432 | .font(InkspringTypography.interface(13)) |
| 1433 | .lineLimit(1...4) |
| 1434 | .textFieldStyle(.plain) |
| 1435 | .padding(.horizontal, 10) |
| 1436 | .padding(.vertical, 8) |
| 1437 | .studioSurface(StudioRadius.control) |
| 1438 | Button("Cancel") { composingRevisionRequest = false } |
| 1439 | Button(StudioRevisionRequestCopy.send) { |
| 1440 | let text = revisionRequest.trimmingCharacters(in: .whitespacesAndNewlines) |
| 1441 | workspace.perform { |
| 1442 | try workspace.addComment(to: current, text: text, revisionRequestID: UUID().uuidString.lowercased()) |
| 1443 | revisionRequest = "" |
| 1444 | composingRevisionRequest = false |
| 1445 | InkspringReview.recordActivity() |
| 1446 | Task { await workspace.runDraftRevisionComments() } |
| 1447 | } |
| 1448 | } |
| 1449 | .disabled(!workspace.writingToolsAvailable || revisionRequest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| 1450 | || revisionRequest.utf16.count > 4_000) |
| 1451 | } |
| 1452 | .disabled(!workspace.writingToolsAvailable) |
| 1453 | } |
| 1454 | if !workspace.writingToolsAvailable { |
| 1455 | Text("Connect a writing agent to send a revision request.").font(.caption).foregroundStyle(palette.muted) |
| 1456 | } |
| 1457 | } |
| 1458 | ForEach(current.revisionRequests) { request in |
| 1459 | StudioRevisionRequestRow(request: .init(request)) |
| 1460 | } |
| 1461 | } |
| 1462 | } |
| 1463 | |
| 1464 | @ViewBuilder private var postArticleControls: some View { |
| 1465 | if record.kind == "draft", record["platform"] == "x", record.fields["manualQuote"] as? Bool != true { |
| 1466 | let key = "xArticleID" |
| 1467 | let allowsChanges = !["queued", "due", "posting", "posted", "uncertain"].contains(record.scheduleStatus) |
| 1468 | let replies = workspace.xReplyArticles(for: record, body: record.body) |
| 1469 | if allowsChanges || !record[key].isEmpty || !replies.isEmpty { |
| 1470 | let canCreate = !record.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && record["format"] != "reply" |
| 1471 | let create: (() -> Void)? = canCreate ? { createLinkedArticle() } : nil |
| 1472 | let hasUnpublishedArticle = replies.contains { $0["state"] != "published" } || workspace.records.contains { |
| 1473 | $0.isXArticle && $0.projectID == record.projectID && $0.id == record[key] && $0["state"] != "published" |
| 1474 | } |
| 1475 | let publish: (() -> Void)? = canCreate && allowsChanges && hasUnpublishedArticle |
| 1476 | ? { postNow(record) } : nil |
| 1477 | PostArticlePicker(workspace: workspace, projectID: record.projectID, |
| 1478 | articleID: articleBinding(key), openArticle: { openArticle($0, record) }, createArticle: create, |
| 1479 | xReplyArticles: replies, allowsChanges: allowsChanges, publishTogether: publish) |
| 1480 | } |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | private func articleBinding(_ key: String) -> Binding<String> { |
| 1485 | Binding(get: { record[key] }, set: { id in |
| 1486 | workspace.perform { |
| 1487 | var updated = record |
| 1488 | updated[key] = id |
| 1489 | try workspace.save(updated) |
| 1490 | } |
| 1491 | }) |
| 1492 | } |
| 1493 | |
| 1494 | private func createLinkedArticle() { |
| 1495 | workspace.perform { |
| 1496 | let article = try workspace.linkedArticleDraft(from: record) |
| 1497 | openArticle(article, record) |
| 1498 | } |
| 1499 | } |
| 1500 | |
| 1501 | private func attachment(_ title: String, icon: String, url: URL?) -> some View { |
| 1502 | VStack(alignment: .leading, spacing: 10) { |
| 1503 | Label(title, systemImage: icon) |
| 1504 | .font(InkspringTypography.interface(12).weight(.semibold)) |
| 1505 | .foregroundStyle(palette.muted) |
| 1506 | if let url { |
| 1507 | AttachedMedia(url: url, videoHeight: expanded ? 420 : 250) |
| 1508 | .frame(maxWidth: .infinity) |
| 1509 | .clipShape(.rect(cornerRadius: StudioRadius.control)) |
| 1510 | } else { |
| 1511 | Label("Attachment unavailable", systemImage: "exclamationmark.circle") |
| 1512 | .foregroundStyle(.secondary) |
| 1513 | } |
| 1514 | } |
| 1515 | .padding(12) |
| 1516 | .studioSurface() |
| 1517 | } |
| 1518 | |
| 1519 | @ViewBuilder private var previewActions: some View { |
| 1520 | if !["posting", "posted"].contains(record.scheduleStatus) { |
| 1521 | if record.offersPostNow { |
| 1522 | Button("Post now…", systemImage: "paperplane") { postNow(record) } |
| 1523 | .modifier(PrimaryActionStyle()) |
| 1524 | .accessibilityIdentifier("post.now") |
| 1525 | } |
| 1526 | Button(record.kind == "idea" ? "Edit idea" : "Edit post", systemImage: "pencil") { |
| 1527 | edit(record) |
| 1528 | } |
| 1529 | if record.kind == "draft" { |
| 1530 | Button("Open in studio", systemImage: "arrow.up.right") { openInStudio(record) } |
| 1531 | } |
| 1532 | } |
| 1533 | } |
| 1534 | |
| 1535 | private var previewMoreActions: some View { |
| 1536 | StudioFilterMenu(title: "More actions", value: "More actions") { |
| 1537 | Button("Copy text", systemImage: "doc.on.doc") { copy(record.body) } |
| 1538 | Button(record["planMarkdown"].isEmpty ? "Add private outline" : "View private outline", |
| 1539 | systemImage: "list.bullet.clipboard") { outlineID = record.id } |
| 1540 | .help("Open notes for this draft. They stay in Inkspring when you publish.") |
| 1541 | Divider() |
| 1542 | Button(record.kind == "idea" ? "Skip idea" : "Move to Trash", systemImage: "trash") { |
| 1543 | workspace.perform { try workspace.trashLibraryItem(record) } |
| 1544 | } |
| 1545 | .disabled(["posting", "posted", "uncertain"].contains(record.scheduleStatus)) |
| 1546 | } |
| 1547 | .help("Copy the text, open private draft notes, or move this item to Trash.") |
| 1548 | } |
| 1549 | } |
| 1550 | |
| 1551 | private struct WorkspaceTrash: View { |
| 1552 | let workspace: Workspace |
| 1553 | @State private var deleting: WorkspaceRecord? |
| 1554 | @Environment(\.studioPalette) private var palette |
| 1555 | |
| 1556 | var body: some View { |
| 1557 | StudioScrollView { |
| 1558 | VStack(alignment: .leading, spacing: 20) { |
| 1559 | PageHeading(title: "Trash", subtitle: "Restore drafts and ideas, or permanently delete them.") |
| 1560 | if workspace.trashedRecords.isEmpty { |
| 1561 | ContentUnavailableView("Trash is empty", systemImage: "trash") |
| 1562 | } |
| 1563 | ForEach(workspace.trashedRecords) { item in |
| 1564 | VStack(alignment: .leading, spacing: 12) { |
| 1565 | Label(item.kind == "idea" ? "Post idea" : "Draft", systemImage: item.kind == "idea" ? "lightbulb" : "doc.text") |
| 1566 | .font(.caption).foregroundStyle(palette.muted) |
| 1567 | Text(item.title).font(.headline) |
| 1568 | Text(item.body).font(.body).lineLimit(3).foregroundStyle(palette.muted) |
| 1569 | HStack { |
| 1570 | Button("Restore", systemImage: "arrow.uturn.backward") { |
| 1571 | workspace.perform { try workspace.restoreLibraryItem(item) } |
| 1572 | } |
| 1573 | Button("Delete permanently…", systemImage: "trash", role: .destructive) { deleting = item } |
| 1574 | } |
| 1575 | }.padding(18).frame(maxWidth: .infinity, alignment: .leading).studioSurface() |
| 1576 | } |
| 1577 | }.padding(32) |
| 1578 | } |
| 1579 | .confirmationDialog("Delete permanently?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) { |
| 1580 | Button("Delete permanently", role: .destructive) { |
| 1581 | if let item = deleting { workspace.perform { try workspace.deleteLibraryItem(item) } } |
| 1582 | deleting = nil |
| 1583 | } |
| 1584 | Button("Cancel", role: .cancel) { deleting = nil } |
| 1585 | } message: { Text("This cannot be undone. Linked posts and media files are kept.") } |
| 1586 | } |
| 1587 | } |
| 1588 | |
| 1589 | struct AttachedMedia: View { |
| 1590 | let url: URL? |
| 1591 | var videoHeight: CGFloat = 250 |
| 1592 | |
| 1593 | var body: some View { |
| 1594 | if let url, ["mp4", "mov", "webm"].contains(url.pathExtension.lowercased()) { |
| 1595 | if FileManager.default.fileExists(atPath: url.path) { |
| 1596 | if url.pathExtension.lowercased() == "webm" { |
| 1597 | AttachedWebMPlayer(url: url).frame(height: videoHeight) |
| 1598 | } else { |
| 1599 | AttachedVideoPlayer(url: url).frame(height: videoHeight) |
| 1600 | } |
| 1601 | } else { |
| 1602 | Label("Video file is unavailable", systemImage: "exclamationmark.circle").foregroundStyle(.secondary) |
| 1603 | } |
| 1604 | } else if let url { |
| 1605 | if let image = NSImage(contentsOf: url) { |
| 1606 | Image(nsImage: image).resizable().scaledToFit().frame(maxHeight: 350) |
| 1607 | .accessibilityLabel("Attached image") |
| 1608 | } else { |
| 1609 | Label("Image file is unavailable", systemImage: "exclamationmark.circle").foregroundStyle(.secondary) |
| 1610 | } |
| 1611 | } |
| 1612 | } |
| 1613 | } |
| 1614 | |
| 1615 | private struct AttachedVideoPlayer: NSViewRepresentable { |
| 1616 | let url: URL |
| 1617 | |
| 1618 | func makeNSView(context: Context) -> AVPlayerView { |
| 1619 | let view = AVPlayerView() |
| 1620 | view.controlsStyle = .inline |
| 1621 | view.videoGravity = .resizeAspect |
| 1622 | return view |
| 1623 | } |
| 1624 | |
| 1625 | func updateNSView(_ view: AVPlayerView, context: Context) { |
| 1626 | let currentURL = (view.player?.currentItem?.asset as? AVURLAsset)?.url |
| 1627 | guard currentURL != url else { return } |
| 1628 | view.player?.pause() |
| 1629 | view.player = AVPlayer(url: url) |
| 1630 | } |
| 1631 | |
| 1632 | static func dismantleNSView(_ view: AVPlayerView, coordinator: ()) { |
| 1633 | view.player?.pause() |
| 1634 | view.player = nil |
| 1635 | } |
| 1636 | } |
| 1637 | |
| 1638 | private struct AttachedWebMPlayer: NSViewRepresentable { |
| 1639 | let url: URL |
| 1640 | |
| 1641 | @MainActor |
| 1642 | final class Coordinator: NSObject, WKNavigationDelegate { |
| 1643 | var url: URL? |
| 1644 | |
| 1645 | func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy { |
| 1646 | navigationAction.request.url == url ? .allow : .cancel |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | func makeCoordinator() -> Coordinator { Coordinator() } |
| 1651 | |
| 1652 | func makeNSView(context: Context) -> WKWebView { |
| 1653 | let configuration = WKWebViewConfiguration() |
| 1654 | configuration.websiteDataStore = .nonPersistent() |
| 1655 | configuration.defaultWebpagePreferences.allowsContentJavaScript = false |
| 1656 | let view = WKWebView(frame: .zero, configuration: configuration) |
| 1657 | view.navigationDelegate = context.coordinator |
| 1658 | return view |
| 1659 | } |
| 1660 | |
| 1661 | func updateNSView(_ view: WKWebView, context: Context) { |
| 1662 | guard context.coordinator.url != url else { return } |
| 1663 | context.coordinator.url = url |
| 1664 | view.loadFileURL(url, allowingReadAccessTo: url) |
| 1665 | } |
| 1666 | |
| 1667 | static func dismantleNSView(_ view: WKWebView, coordinator: Coordinator) { |
| 1668 | view.pauseAllMediaPlayback(completionHandler: nil) |
| 1669 | view.stopLoading() |
| 1670 | view.navigationDelegate = nil |
| 1671 | } |
| 1672 | } |
| 1673 | |
| 1674 | @MainActor |
| 1675 | func copy(_ text: String) { |
| 1676 | NSPasteboard.general.clearContents() |
| 1677 | NSPasteboard.general.setString(text, forType: .string) |
| 1678 | } |
| 1679 | |
| 1680 | private struct StatusGlass: ViewModifier { |
| 1681 | @Environment(\.studioPalette) private var palette |
| 1682 | |
| 1683 | @ViewBuilder func body(content: Content) -> some View { |
| 1684 | if palette.theme == .paper { |
| 1685 | content.studioPaperControl(in: Capsule(), fill: palette.control) |
| 1686 | } else if #available(macOS 26, *) { |
| 1687 | content.glassEffect(.regular.interactive(), in: .capsule) |
| 1688 | } else { |
| 1689 | content.background(.regularMaterial, in: Capsule()) |
| 1690 | } |
| 1691 | } |
| 1692 | } |
| 1693 | |
| 1694 | struct PrimaryActionStyle: ViewModifier { |
| 1695 | func body(content: Content) -> some View { |
| 1696 | content.buttonStyle(StudioActionStyle(prominent: true)) |
| 1697 | } |
| 1698 | } |