Branchwell

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

Raw 71.3 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import InkspringSchedule
2import ServiceManagement
3import SwiftUI
4
5struct WorkspaceSettings: View {
6 let workspace: Workspace
7 @Environment(\.studioPalette) private var palette
8 @State private var section: String
9 private let sections = [
10 ("Appearance", "circle.lefthalf.filled"),
11 ("Voice & projects", "text.quote"),
12 ("Ideas & sources", "lightbulb"),
13 ("Preferred schedules", "calendar"),
14 ("AI models", "sparkles"),
15 ("AI agents", "bubble.left.and.text.bubble.right"),
16 ("API keys", "key"),
17 ("Connections", "link"),
18 ("Storage & backups", "externaldrive"),
19 ("Support", "questionmark.circle")
20 ]
21
22 init(workspace: Workspace, initialSection: String = "Appearance") {
23 self.workspace = workspace
24 _section = State(initialValue: initialSection)
25 }
26
27 var body: some View {
28 VStack(alignment: .leading, spacing: 18) {
29 PageHeading(title: "Settings")
30 .padding(.top, 24)
31 .padding(.horizontal, 24)
32 HStack(alignment: .top, spacing: 0) {
33 sectionList
34 .frame(width: 164)
35 .padding(.leading, 18)
36 .padding(.trailing, 12)
37 StudioRule(axis: .vertical)
38 settingsContent.id(section)
39 }
40 .frame(maxHeight: .infinity)
41 }
42 .frame(maxWidth: 1120, alignment: .topLeading)
43 .frame(maxWidth: .infinity, alignment: .center)
44 }
45
46 private var sectionList: some View {
47 VStack(alignment: .leading, spacing: 3) {
48 ForEach(sections, id: \.0) { title, icon in
49 Button { section = title } label: {
50 HStack(spacing: 8) {
51 Image(systemName: icon)
52 .foregroundStyle(palette.iconAccent)
53 .frame(width: 17)
54 .accessibilityHidden(true)
55 Text(title)
56 .font(InkspringTypography.interface(13).weight(section == title ? .semibold : .regular))
57 .fixedSize(horizontal: false, vertical: true)
58 }
59 .foregroundStyle(section == title ? palette.text : palette.muted)
60 .padding(.horizontal, 9)
61 .padding(.vertical, 7)
62 .frame(maxWidth: .infinity, minHeight: 32, alignment: .leading)
63 .contentShape(Rectangle())
64 }
65 .buttonStyle(StudioRowStyle(selected: section == title, indicator: true))
66 .accessibilityAddTraits(section == title ? .isSelected : [])
67 }
68 }
69 .accessibilityElement(children: .contain)
70 .accessibilityLabel("Settings sections")
71 }
72
73 private var settingsContent: some View {
74 StudioScrollView {
75 VStack(alignment: .leading, spacing: 18) {
76 if section != "Appearance" {
77 Text(section)
78 .font(InkspringTypography.editorial(26, relativeTo: .title2))
79 .accessibilityAddTraits(.isHeader)
80 }
81 switch section {
82 case "Appearance": StudioThemeSettings(workspace: workspace)
83 case "AI models": ModelPreferences(workspace: workspace)
84 case "Preferred schedules": preferredSchedules
85 case "API keys":
86 SetupHelpLink("API key setup and troubleshooting", topic: "api-keys")
87 Text("OpenAI and Gemini keys enable image generation. Anthropic, OpenAI, and Gemini keys also support optional API writing. Apify and X keys fetch public research and posts.")
88 .foregroundStyle(.secondary)
89 ForEach(ProviderKey.allCases) { ProviderKeyRow(provider: $0, workspace: workspace) }
90 case "Ideas & sources":
91 GroupBox("Automatic idea refill") {
92 VStack(alignment: .leading, spacing: 12) {
93 Toggle("Refill ideas while Inkspring is open", isOn: Binding(get: {
94 workspace.settings["ideaQueueAutomatic"] as? Bool == true
95 }, set: { enabled in
96 workspace.perform { try workspace.set("ideaQueueAutomatic", to: enabled) }
97 }))
98 StudioLabeledChoice(title: "Target number of open ideas", selection: Binding(
99 get: { IdeaQueuePlan.target(workspace.settings["ideaQueueTarget"]) },
100 set: { value in workspace.perform { try workspace.set("ideaQueueTarget", to: value) } }
101 ), options: IdeaQueuePlan.targets, label: { $0.formatted() })
102 Text("Refill pauses at your target. You can keep adding ideas yourself.")
103 .font(.callout).foregroundStyle(.secondary)
104 }
105 }
106 VaultSettings(workspace: workspace)
107 WorkSourceSettings(workspace: workspace)
108 case "Storage & backups":
109 BackupControls(workspace: workspace)
110 CompanionSyncSettings(workspace: workspace)
111 R2Settings(workspace: workspace)
112 case "Connections":
113 SetupHelpLink("Connection setup and troubleshooting", topic: "connections")
114 GroupBox("LinkedIn") {
115 DeveloperConnectionSettings(workspace: workspace, platform: .linkedin, initiallyExpanded: true)
116 }
117 .task { workspace.perform { try workspace.socialAccounts.loadSavedConnections() } }
118 case "AI agents":
119 AgentSettings(workspace: workspace)
120 case "Support":
121 InkspringSupport()
122 default:
123 PersonalProfileSettings(workspace: workspace)
124 }
125 }
126 .frame(maxWidth: .infinity, alignment: .leading)
127 .padding(.horizontal, 22)
128 .padding(.bottom, 24)
129 }
130 }
131
132 private var preferredSchedules: some View {
133 VStack(alignment: .leading, spacing: 14) {
134 Text("Set the hours and default posting minute for each platform. iPhone and iPad use these hours in your Mac’s time zone.")
135 .foregroundStyle(.secondary)
136 ForEach(SocialPlatform.allCases) { platform in
137 let key = platform.rawValue
138 let window = workspace.postingWindow(for: key)
139 let minute = workspace.postingMinute(for: key)
140 VStack(alignment: .leading, spacing: 10) {
141 StudioPlatformLabel(name: key, title: platform.name).font(.headline)
142 StudioLabeledChoice(title: "First posting hour", selection: Binding(
143 get: { window.firstHour },
144 set: { updateSchedule(key, window: CompanionPostingWindow(firstHour: $0, lastHour: window.lastHour), minute: minute) }
145 ), options: Array(0...23), label: postingHourLabel)
146 StudioLabeledChoice(title: "Last posting hour", selection: Binding(
147 get: { window.lastHour },
148 set: { updateSchedule(key, window: CompanionPostingWindow(firstHour: window.firstHour, lastHour: $0), minute: minute) }
149 ), options: Array(window.firstHour...23), label: postingHourLabel)
150 StudioLabeledChoice(title: "Posting minute", selection: Binding(
151 get: { minute },
152 set: { updateSchedule(key, window: window, minute: $0) }
153 ), options: Array(-1...59), label: { $0 < 0 ? "Choose automatically" : String(format: ":%02d", $0) })
154 }
155 .padding(14)
156 .studioSurface()
157 }
158 }
159 }
160
161 private func postingHourLabel(_ hour: Int) -> String {
162 Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: .now)?
163 .formatted(date: .omitted, time: .shortened) ?? String(format: "%02d:00", hour)
164 }
165
166 private func updateSchedule(_ platform: String, window: CompanionPostingWindow, minute: Int) {
167 workspace.perform { try workspace.setPostingPreferences(for: platform, window: window, minute: minute) }
168 }
169}
170
171private struct StudioThemeSettings: View {
172 @Environment(\.studioPalette) private var palette
173 let workspace: Workspace
174
175 private var selection: StudioTheme { StudioTheme(preference: workspace.settings[StudioTheme.preferenceKey]) }
176
177 var body: some View {
178 VStack(alignment: .leading, spacing: 16) {
179 VStack(alignment: .leading, spacing: 5) {
180 Text("Appearance")
181 .font(InkspringTypography.editorial(26, relativeTo: .title2))
182 .accessibilityAddTraits(.isHeader)
183 Text("Choose how Inkspring looks on this Mac.").foregroundStyle(palette.muted)
184 }
185 LazyVGrid(columns: [GridItem(.adaptive(minimum: 165), spacing: 12)], spacing: 12) {
186 ForEach([StudioTheme.graphite, .paper, .light]) { theme in
187 choice(theme)
188 }
189 }
190 Toggle("Follow macOS light/dark appearance", isOn: Binding(
191 get: { selection == .system },
192 set: { choose($0 ? .system : .light) }
193 ))
194
195 }
196 .frame(maxWidth: 725, alignment: .leading)
197 .transaction { $0.animation = nil }
198 }
199
200 private func choice(_ theme: StudioTheme) -> some View {
201 let swatch = StudioPalette(theme: theme)
202 let active = selection == theme
203 return Button { choose(theme) } label: {
204 VStack(alignment: .leading, spacing: 10) {
205 themePreview(swatch)
206 HStack {
207 Text(theme.title).fontWeight(.semibold)
208 Spacer(minLength: 4)
209 Image(systemName: "checkmark.circle.fill")
210 .foregroundStyle(palette.iconAccent)
211 .opacity(active ? 1 : 0)
212 .accessibilityHidden(true)
213 }
214 }
215 .padding(9)
216 .frame(maxWidth: .infinity, alignment: .leading)
217 .studioSurface(fill: active ? palette.active : palette.card)
218 }
219 .buttonStyle(.plain)
220 .accessibilityLabel(theme.title)
221 .accessibilityAddTraits(active ? .isSelected : [])
222 }
223
224 private func themePreview(_ swatch: StudioPalette) -> some View {
225 HStack(spacing: 7) {
226 VStack(alignment: .leading, spacing: 5) {
227 Capsule().fill(swatch.iconAccent).frame(width: 20, height: 3)
228 Capsule().fill(swatch.muted).frame(width: 16, height: 2)
229 Capsule().fill(swatch.muted).frame(width: 11, height: 2)
230 }
231 .frame(width: 40, height: 66)
232 .background(swatch.sidebar)
233
234 VStack(alignment: .leading, spacing: 5) {
235 Capsule().fill(swatch.text).frame(width: 42, height: 4)
236 Rectangle().fill(swatch.line).frame(height: 1)
237 HStack(spacing: 5) {
238 VStack(alignment: .leading, spacing: 4) {
239 RoundedRectangle(cornerRadius: 2).fill(swatch.active).frame(height: 8)
240 RoundedRectangle(cornerRadius: 2).fill(swatch.well).frame(height: 6)
241 }
242 .frame(width: 25)
243 RoundedRectangle(cornerRadius: 3).fill(swatch.card)
244 .overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(swatch.line))
245 }
246 }
247 .padding(.trailing, 7)
248 .padding(.vertical, 9)
249 }
250 .frame(height: 66)
251 .background(swatch.canvas)
252 .clipShape(.rect(cornerRadius: StudioRadius.row))
253 .accessibilityHidden(true)
254 }
255
256 private func choose(_ theme: StudioTheme) {
257 guard selection != theme else { return }
258 workspace.perform { try workspace.set(StudioTheme.preferenceKey, to: theme.rawValue) }
259 }
260}
261
262struct ProviderKeyRow: View {
263 let provider: ProviderKey
264 let workspace: Workspace
265 @State private var key = ""
266 @State private var saved = false
267
268 var body: some View {
269 GroupBox {
270 HStack {
271 SecureField(saved ? "Replace key" : "API key", text: $key).studioInput()
272 Button("Save key") {
273 workspace.perform {
274 try provider.save(key)
275 key = ""
276 saved = true
277 }
278 }
279 .disabled(key.isEmpty)
280 if saved {
281 Button("Remove") {
282 workspace.perform {
283 try provider.remove()
284 saved = false
285 }
286 }
287 }
288 StudioExternalLink("Get a key", destination: provider.managementURL)
289 SetupHelpLink("Setup help", topic: "key-" + provider.rawValue,
290 description: "\(provider.name) API key setup and troubleshooting")
291 }
292 } label: {
293 Label {
294 Text(saved ? "\(provider.name) · saved in Keychain" : provider.name)
295 } icon: {
296 PlatformMark(name: provider.rawValue, fallback: "square.stack.3d.up")
297 }
298 }
299 .onAppear { saved = provider.isSaved }
300 }
301}
302
303struct ModelPreferences: View {
304 @Environment(\.studioPalette) private var palette
305 let workspace: Workspace
306 private var agent: StudioChatAgent { .writingAgent(settings: workspace.settings) }
307 private let catalog = ProviderCatalog.bundled
308 @State private var checking = false
309 @State private var checkMessage: String?
310
311 var body: some View {
312 VStack(alignment: .leading, spacing: 14) {
313 let connection = StudioWritingConnection(settings: workspace.settings)
314 StudioLabeledChoice(title: "Writing connection", selection: Binding(get: { connection }, set: { value in
315 workspace.perform { try workspace.set(StudioWritingConnection.preferenceKey, to: value.rawValue) }
316 }), options: [.agent, .api], label: { $0 == .agent ? "Connected agent" : "Provider API key" })
317 if connection == .agent {
318 StudioLabeledChoice(title: "Writing agent", selection: Binding(get: { agent }, set: { newValue in
319 workspace.perform { try workspace.set(StudioChatAgent.writingPreference, to: newValue.rawValue) }
320 }), options: [.claude, .codex, .gemini], label: { $0.title },
321 icon: { StudioAgentMark.menuImage($0, palette: palette) })
322 StudioLabeledChoice(title: "Writing model", selection: Binding(
323 get: { agent.preferredWritingModel(settings: workspace.settings) ?? "" },
324 set: { model in workspace.perform { try workspace.set(agent.modelPreferenceKey, to: model) } }
325 ), options: (agent == .gemini ? [] : [""]) + agent.writingModels.map(\.id),
326 label: { id in agent.writingModels.first { $0.id == id }?.name ?? "Agent default" })
327 Text(agent == .gemini ? "Uses the Google account signed into Antigravity CLI on this Mac. Model access depends on your Google plan." : "Uses your agent’s signed-in session. Enable access in Settings → AI agents.")
328 .font(.caption).foregroundStyle(.secondary)
329 if agent == .gemini {
330 Link("Set up Antigravity CLI", destination: URL(string: "https://antigravity.google/docs/getting-started?tab=cli")!)
331 } else {
332 SetupHelpLink("Writing agent setup and troubleshooting", topic: "writing-agent")
333 }
334 } else {
335 SetupHelpLink("API key setup and troubleshooting", topic: "api-keys")
336 StudioLabeledChoice(title: "Writing provider", selection: setting("provider"),
337 options: ["anthropic", "openai", "gemini"], label: { ProviderKey(rawValue: $0)?.name ?? $0 },
338 icon: PlatformMark.image)
339 let provider = WritingProviders(settings: workspace.settings).writingProvider
340 let models = switch provider {
341 case .openai: catalog?.openai
342 case .gemini: catalog?.gemini
343 default: catalog?.anthropic
344 }
345 modelPicker("Writing model", key: provider.rawValue + "Model", models: models ?? [])
346 if provider == .anthropic {
347 HStack {
348 StudioAgentMark(agent: .claude)
349 TextField("Claude workspace ID (optional)", text: setting("anthropicWorkspaceId")).studioInput()
350 }
351 }
352 }
353 HStack {
354 Button("Test writing connection") { Task { await checkWritingConnection() } }
355 .disabled(checking)
356 if checking { ProgressView().controlSize(.small) }
357 }
358 if let checkMessage { Text(checkMessage).font(.caption).foregroundStyle(.secondary) }
359 StudioRule()
360 StudioLabeledChoice(title: "Image provider", selection: setting("imageProvider"),
361 options: ["openai", "gemini"], label: { $0 == "openai" ? "OpenAI" : "Gemini" },
362 icon: PlatformMark.image)
363 Text("Generating image files uses an OpenAI or Gemini API key. Writing the image prompt uses your writing connection.")
364 .font(.caption).foregroundStyle(.secondary)
365 let gemini = setting("imageProvider").wrappedValue == "gemini"
366 modelPicker("Image model", key: gemini ? "geminiImageModel" : "openaiImageModel",
367 models: (gemini ? catalog?.geminiImage : catalog?.openaiImage) ?? [],
368 providerIcon: gemini ? "gemini" : "openai")
369 }
370 .frame(maxWidth: 480, alignment: .leading)
371 }
372
373 private func checkWritingConnection() async {
374 guard !checking else { return }
375 checking = true
376 checkMessage = nil
377 defer { checking = false }
378 do {
379 if StudioWritingConnection(settings: workspace.settings) == .agent {
380 let model = ContentStudio(workspace: workspace).model
381 let response = try await model.object("Return exactly the JSON object {\"ok\": true}.", [:])
382 guard response["ok"] as? Bool == true else {
383 throw WorkspaceError("The agent returned an unexpected connection check response.")
384 }
385 checkMessage = "\(model.name) completed the writing check."
386 } else {
387 let providers = WritingProviders(settings: workspace.settings)
388 try await providers.checkWritingConnection()
389 checkMessage = "\(providers.writingProvider.name) accepted the key for \(providers.writingModel)."
390 }
391 } catch {
392 checkMessage = error.localizedDescription
393 }
394 }
395
396 private func setting(_ key: String) -> Binding<String> {
397 Binding(get: {
398 let value = workspace.settings[key] as? String ?? catalog?.defaults[key] ?? ""
399 return key == "anthropicModel" ? ProviderKey.anthropic.currentModelID(value) : value
400 },
401 set: { value in workspace.perform { try workspace.set(key, to: value) } })
402 }
403
404 private func modelPicker(_ label: String, key: String, models: [ProviderCatalog.Model],
405 providerIcon: String? = nil) -> some View {
406 let current = setting(key)
407 let ids = models.map(\.id)
408 return StudioLabeledChoice(title: label, selection: current,
409 options: ids.contains(current.wrappedValue) ? ids : [current.wrappedValue] + ids,
410 label: { id in models.first(where: { $0.id == id })?.name ?? (id.isEmpty ? "Default" : id) },
411 icon: { id in
412 if let providerIcon { return PlatformMark.image(providerIcon) }
413 return id.hasPrefix("claude-") ? StudioAgentMark.menuImage(.claude, palette: palette) : nil
414 })
415 }
416}
417
418struct PersonalProfileSettings: View {
419 let workspace: Workspace
420 @State private var profile: [String: Any] = [:]
421 @State private var savedProfile: [String: Any] = [:]
422 @State private var hashtags = ""
423 @State private var learning: Task<Void, Never>?
424 @State private var showingHistory = false
425 @State private var history: [WorkspaceRecord] = []
426 @State private var selectedSamples: Set<String> = []
427 @State private var sampleError: String?
428 @State private var reviewedSuggestion: WorkspaceRecord?
429 @State private var needsSave = false
430
431 private var hasSamples: Bool {
432 !(profile["samples"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
433 }
434
435 private var hasChanges: Bool {
436 needsSave || reviewedSuggestion != nil || NSDictionary(dictionary: profile) != NSDictionary(dictionary: savedProfile)
437 || hashtags != (savedProfile["hashtags"] as? [String] ?? []).joined(separator: ", ")
438 }
439
440 var body: some View {
441 VStack(alignment: .leading, spacing: 18) {
442 GroupBox {
443 VStack(alignment: .leading, spacing: 12) {
444 Text("Personal profile").font(.headline)
445 TextField("Writing style", text: field("voice"), axis: .vertical).studioInput()
446 TextField("Visual style", text: field("imageStyle"), axis: .vertical).studioInput()
447 TextField("Interests", text: field("interests"), axis: .vertical).studioInput()
448 TextField("What to avoid", text: field("avoid"), axis: .vertical).studioInput()
449 TextField("Writing samples", text: field("samples"), axis: .vertical)
450 .lineLimit(3...8)
451 .textFieldStyle(.plain)
452 .padding(12)
453 .studioSurface(StudioRadius.control)
454 HStack {
455 Button("Choose from published drafts…") {
456 history = PersonalProfile.publishedDrafts(in: workspace.records)
457 selectedSamples = []
458 sampleError = nil
459 showingHistory = true
460 }
461 Button("Suggest my voice", systemImage: "sparkles", action: learnVoice)
462 .disabled(!hasSamples)
463 if learning != nil { ProgressView().controlSize(.small) }
464 }
465 Text(hasSamples
466 ? "Your selected writing connection uses these samples to suggest a profile for you to review."
467 : "Paste a writing sample or choose a published draft to enable Suggest my voice.")
468 .font(.callout)
469 .foregroundStyle(.secondary)
470 TextField("Hashtags, separated by commas", text: $hashtags).studioInput()
471 }
472 }
473 GroupBox("Research sources for post ideas") {
474 VStack(alignment: .leading, spacing: 10) {
475 Text("Choose which feeds Inkspring can use when suggesting post ideas.")
476 .font(.callout).foregroundStyle(.secondary)
477 LazyVGrid(columns: [GridItem(.adaptive(minimum: 190), spacing: 10)], alignment: .leading, spacing: 8) {
478 ForEach(PersonalProfile.sourceNames, id: \.self) { source in
479 Toggle(isOn: Binding(get: {
480 (profile["researchSources"] as? [String] ?? ["x", "news"]).contains(source)
481 }, set: { enabled in
482 var sources = Set(profile["researchSources"] as? [String] ?? ["x", "news"])
483 if enabled { sources.insert(source) } else { sources.remove(source) }
484 profile["researchSources"] = Array(sources)
485 })) {
486 Label { Text(platformName(source)) } icon: { PlatformMark(name: source, fallback: "newspaper") }
487 }
488 }
489 }
490 }
491 .frame(maxWidth: .infinity, alignment: .leading)
492 }
493 HStack {
494 Button(reviewedSuggestion == nil ? "Save profile" : "Save reviewed profile", action: save)
495 .modifier(PrimaryActionStyle())
496 .disabled(!hasChanges)
497 if hasChanges { Button("Reload saved profile", action: reload) }
498 }
499 if let reviewedSuggestion {
500 Text("Review the suggested profile from \(reviewedSuggestion["origin"].isEmpty ? "your agent" : reviewedSuggestion["origin"]).")
501 .font(.caption).foregroundStyle(.secondary)
502 } else if needsSave {
503 Text("Review the suggested voice, interests, and things to avoid, then save your profile.")
504 .font(.caption).foregroundStyle(.secondary)
505 }
506 SuggestionInbox(workspace: workspace, reviewProfile: loadSuggestion) { item in
507 if reviewedSuggestion?.id == item.id { reviewedSuggestion = nil }
508 }
509 }
510 .disabled(learning != nil)
511 .frame(maxWidth: 640, alignment: .leading)
512 .onAppear(perform: reload)
513 .onDisappear { learning?.cancel() }
514 .sheet(isPresented: $showingHistory) { samplePicker }
515 }
516
517 private var samplePicker: some View {
518 VStack(alignment: .leading, spacing: 16) {
519 Text("Choose writing samples").font(.title2)
520 if history.isEmpty {
521 ContentUnavailableView("No published drafts", systemImage: "text.document",
522 description: Text("You can paste your own examples in Writing samples."))
523 .frame(maxWidth: .infinity)
524 } else {
525 StudioScrollView {
526 LazyVStack(alignment: .leading, spacing: 12) {
527 ForEach(history) { draft in
528 Toggle(isOn: Binding(get: { selectedSamples.contains(draft.id) }, set: { selected in
529 if selected { selectedSamples.insert(draft.id) } else { selectedSamples.remove(draft.id) }
530 sampleError = nil
531 })) {
532 VStack(alignment: .leading, spacing: 4) {
533 Text(draft.title + " · " + platformName(draft["platform"])).font(.headline)
534 Text(draft.body).lineLimit(5).foregroundStyle(.secondary)
535 }
536 }
537 }
538 }
539 .frame(maxWidth: .infinity, alignment: .leading)
540 }
541 .frame(maxHeight: 360)
542 }
543 if let sampleError { Text(sampleError).foregroundStyle(.red) }
544 HStack {
545 Button("Cancel", role: .cancel) { showingHistory = false }
546 Spacer()
547 Button("Add selected examples") {
548 do {
549 profile["samples"] = try PersonalProfile.samples(appending: history.filter { selectedSamples.contains($0.id) },
550 to: profile["samples"] as? String ?? "")
551 showingHistory = false
552 } catch { sampleError = error.localizedDescription }
553 }
554 .disabled(selectedSamples.isEmpty)
555 .keyboardShortcut(.defaultAction)
556 }
557 }
558 .padding(24)
559 .frame(width: 580)
560 }
561
562 private func learnVoice() {
563 guard learning == nil else { return }
564 let samples = profile["samples"] as? String ?? ""
565 let studio = ContentStudio(workspace: workspace)
566 learning = Task { @MainActor in
567 defer { learning = nil }
568 do {
569 let suggestion = try await studio.learnWritingStyle(from: samples)
570 try Task.checkCancellation()
571 for (key, value) in suggestion { profile[key] = value }
572 needsSave = true
573 } catch {
574 if !Task.isCancelled { workspace.error = error.localizedDescription }
575 }
576 }
577 }
578
579 private func save() {
580 workspace.perform {
581 var draft = profile
582 draft["hashtags"] = hashtags.split(separator: ",").map(String.init)
583 try workspace.savePersonalProfile(draft, replacing: savedProfile, suggestionID: reviewedSuggestion?.id)
584 reload()
585 workspace.notice = "Profile saved"
586 }
587 }
588
589 private func loadSuggestion(_ item: WorkspaceRecord) {
590 guard let proposal = item.fields["profile"] as? [String: Any] else { return }
591 profile = proposal
592 hashtags = (proposal["hashtags"] as? [String] ?? []).joined(separator: ", ")
593 reviewedSuggestion = item
594 needsSave = false
595 }
596
597 private func reload() {
598 profile = workspace.settings["personalProfile"] as? [String: Any] ?? [:]
599 savedProfile = profile
600 hashtags = (profile["hashtags"] as? [String] ?? []).joined(separator: ", ")
601 reviewedSuggestion = nil
602 needsSave = false
603 }
604
605 private func field(_ key: String) -> Binding<String> {
606 Binding(get: { profile[key] as? String ?? "" }, set: { profile[key] = $0 })
607 }
608}
609
610private struct SuggestionInbox: View {
611 let workspace: Workspace
612 let reviewProfile: (WorkspaceRecord) -> Void
613 let dismissed: (WorkspaceRecord) -> Void
614
615 var body: some View {
616 let pending = workspace.records.filter { $0.kind == "personal-inbox" && $0["status"] == "pending" }
617 if !pending.isEmpty {
618 Divider()
619 Text("Ideas from your agent").font(.headline)
620 ForEach(pending) { suggestion in
621 GroupBox(suggestion["kind"] == "profile" ? "Profile suggestion" : suggestion.title) {
622 VStack(alignment: .leading, spacing: 8) {
623 if suggestion["kind"] == "profile", let profile = suggestion.fields["profile"] as? [String: Any] {
624 ForEach(PersonalProfile.textLimits.keys.sorted(), id: \.self) { key in
625 if let value = profile[key] as? String, !value.isEmpty {
626 LabeledContent(key == "imageStyle" ? "Visual style" : key.capitalized) { Text(value) }
627 }
628 }
629 } else {
630 Text(suggestion["summary"]).textSelection(.enabled)
631 }
632 HStack {
633 if suggestion["kind"] == "profile" {
634 Button("Review suggested profile") { reviewProfile(suggestion) }
635 } else {
636 Button("Accept") { review(suggestion, accept: true) }
637 }
638 Button("Dismiss") { review(suggestion, accept: false) }
639 }
640 }
641 .frame(maxWidth: .infinity, alignment: .leading)
642 }
643 }
644 }
645 }
646
647 private func review(_ item: WorkspaceRecord, accept: Bool) {
648 workspace.perform {
649 try workspace.reviewSuggestion(item.id, accept: accept)
650 if !accept { dismissed(item) }
651 }
652 }
653}
654
655struct WorkspaceConnections: View {
656 @Environment(\.studioPalette) private var palette
657
658 private enum ConnectionCheck {
659 case verified(String)
660 case failed(String)
661 }
662
663 let workspace: Workspace
664 @State private var disconnecting: SocialPlatform?
665 @State private var loading = false
666 @State private var testing: SocialPlatform?
667 @State private var connectionChecks: [SocialPlatform: ConnectionCheck] = [:]
668
669 private var accounts: ManagedSocialAccounts { workspace.socialAccounts }
670
671 var body: some View {
672 StudioScrollView {
673 VStack(alignment: .leading, spacing: 16) {
674 HStack {
675 PageHeading(title: "Your channels. Your call.",
676 subtitle: "Manage the accounts Inkspring can use for publishing and analytics.")
677 Spacer()
678 SetupHelpLink("Connection help", topic: "connections")
679 Button("Refresh", systemImage: "arrow.clockwise") { Task { await load() } }
680 .disabled(loading || accounts.connecting != nil || testing != nil)
681 }
682 ForEach(SocialPlatform.allCases) { platform in
683 GroupBox {
684 HStack {
685 if let profile = accounts.profiles[platform] {
686 VStack(alignment: .leading, spacing: 4) {
687 HStack(spacing: 5) {
688 Image(systemName: "checkmark.circle.fill").accessibilityHidden(true)
689 Text("Connected").fontWeight(.semibold)
690 }
691 .foregroundStyle(palette.success)
692 Text(profile.displayName).foregroundStyle(palette.muted)
693 if platform == .tiktok {
694 Text(profile.usesDeveloperApp ? "Using your TikTok developer app" : "Using Inkspring’s shared TikTok app")
695 .font(.caption).foregroundStyle(palette.muted)
696 }
697 }
698 Spacer()
699 if testing == platform || accounts.connecting == platform { ProgressView().controlSize(.small) }
700 Button("Test connection") { Task { await testConnection(platform) } }
701 .disabled(testing != nil || accounts.connecting != nil)
702 Button("Reconnect…") { Task { await connect(platform, developerApp: profile.usesDeveloperApp) } }
703 .disabled(accounts.connecting != nil || testing != nil)
704 Button("Disconnect…") { disconnecting = platform }
705 .disabled(accounts.connecting != nil || testing != nil)
706 } else if platform == .x {
707 VStack(alignment: .leading, spacing: 4) {
708 Text("Set up X posting").fontWeight(.semibold)
709 Text("Connect your own X developer app. Posting uses its API credits and limits.")
710 .foregroundStyle(.secondary)
711 }
712 Spacer()
713 } else if platform == .linkedin {
714 let sharedSignIn = accounts.availability.contains(.linkedin)
715 let canConnect = sharedSignIn || accounts.developerAppIDs[.linkedin] != nil
716 VStack(alignment: .leading, spacing: 4) {
717 Text(canConnect ? "Connect your LinkedIn profile" : "Set up LinkedIn posting")
718 .fontWeight(.semibold)
719 Text(canConnect
720 ? "Sign in to LinkedIn and give Inkspring permission to publish as you."
721 : "Save your developer app credentials below, then sign in to your LinkedIn profile.")
722 .foregroundStyle(.secondary)
723 }
724 Spacer()
725 if accounts.connecting == platform { ProgressView().controlSize(.small) }
726 if canConnect {
727 Button("Connect LinkedIn…") {
728 Task { await connect(.linkedin, developerApp: !sharedSignIn) }
729 }
730 .help("Open LinkedIn to sign in and approve publishing access for your profile.")
731 .disabled(accounts.connecting != nil || loading || testing != nil)
732 }
733 } else {
734 Text(accounts.availability.contains(platform) ? "Sign in with Inkspring" : "Shared sign-in unavailable")
735 .foregroundStyle(.secondary)
736 Spacer()
737 if accounts.connecting == platform { ProgressView().controlSize(.small) }
738 Button("Connect…") { Task { await connect(platform) } }
739 .disabled(accounts.connecting != nil || loading || !accounts.availability.contains(platform))
740 }
741 }
742 .frame(maxWidth: .infinity, alignment: .leading)
743 if let check = connectionChecks[platform] {
744 switch check {
745 case let .verified(name):
746 Label("Verified account \(name)", systemImage: "checkmark.circle")
747 .foregroundStyle(.secondary)
748 case let .failed(message):
749 Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.red)
750 }
751 }
752 DeveloperConnectionSettings(
753 workspace: workspace, platform: platform,
754 initiallyExpanded: platform == .x && accounts.profiles[platform] == nil,
755 showsConnectButton: platform != .linkedin || accounts.availability.contains(.linkedin)
756 || accounts.profiles[.linkedin] != nil
757 )
758 .padding(.top, 7)
759 if platform == .linkedin && accounts.profiles[.linkedin] != nil {
760 Button("Refresh LinkedIn company pages") {
761 Task {
762 do { try await accounts.refreshLinkedInPages() }
763 catch { workspace.error = error.localizedDescription }
764 }
765 }
766 ForEach(accounts.linkedInDestinations) { page in
767 Text(page.name).foregroundStyle(.secondary)
768 }
769 }
770 } label: {
771 Label { Text(platform.name) } icon: { PlatformMark(name: platform.rawValue) }
772 }
773 }
774 SubstackConnectionSettings(workspace: workspace)
775 PublishingHistory(workspace: workspace)
776 }
777 .studioPage()
778 }
779 .task { await load() }
780 .onChange(of: accounts.profiles) { old, new in
781 for platform in SocialPlatform.allCases where old[platform] != new[platform] {
782 connectionChecks[platform] = nil
783 }
784 }
785 .confirmationDialog("Disconnect this social account?", isPresented: Binding(
786 get: { disconnecting != nil }, set: { if !$0 { disconnecting = nil } }
787 )) {
788 Button("Disconnect", role: .destructive) {
789 guard let platform = disconnecting else { return }
790 workspace.perform { try accounts.disconnect(platform) }
791 disconnecting = nil
792 }
793 }
794 }
795
796 private func connect(_ platform: SocialPlatform, developerApp: Bool = false) async {
797 connectionChecks[platform] = nil
798 do { try await accounts.connect(platform, developerApp: developerApp) }
799 catch is CancellationError {}
800 catch { workspace.error = error.localizedDescription }
801 }
802
803 private func testConnection(_ platform: SocialPlatform) async {
804 guard testing == nil else { return }
805 testing = platform
806 connectionChecks[platform] = nil
807 defer { testing = nil }
808 do {
809 let profile = try await accounts.testConnection(platform)
810 if platform == .tiktok {
811 let creator = try await SocialPublisher(workspace: workspace).tikTokCreator()
812 let directPost = creator.privacy.contains("PUBLIC_TO_EVERYONE")
813 ? "Direct Post allows Everyone"
814 : "Direct Post has no Everyone option"
815 connectionChecks[platform] = .verified(profile.displayName + " · " + directPost)
816 } else {
817 connectionChecks[platform] = .verified(profile.displayName)
818 }
819 } catch is CancellationError {
820 } catch {
821 if accounts.profiles[platform] != nil { connectionChecks[platform] = .failed(error.localizedDescription) }
822 }
823 }
824
825 private func load() async {
826 guard !loading else { return }
827 loading = true
828 defer { loading = false }
829 do { try await accounts.load() }
830 catch { workspace.error = error.localizedDescription }
831 }
832}
833
834struct AboutInkspring: View {
835 @Environment(\.studioPalette) private var palette
836
837 var body: some View {
838 StudioScrollView {
839 VStack(alignment: .leading, spacing: 24) {
840 masthead
841 InkspringSupportButton()
842 InkspringSupportCards()
843 VStack(spacing: 16) {
844 StudioRule()
845 ViewThatFits(in: .horizontal) {
846 HStack {
847 siteLinks
848 Spacer(minLength: 24)
849 copyright
850 }
851 VStack(alignment: .leading, spacing: 12) {
852 ViewThatFits(in: .horizontal) {
853 siteLinks
854 VStack(alignment: .leading, spacing: 8) {
855 ProtomotaProductPill()
856 projectLinks
857 }
858 }
859 copyright
860 }
861 .frame(maxWidth: .infinity, alignment: .leading)
862 }
863 }
864 }
865 .frame(maxWidth: 980)
866 .studioPage()
867 }
868 }
869
870 private var masthead: some View {
871 VStack(alignment: .leading, spacing: 18) {
872 HStack(alignment: .center, spacing: 24) {
873 InkspringBrandIcon(width: 100, height: 88, radius: 22)
874 VStack(alignment: .leading, spacing: 5) {
875 Text("Inkspring")
876 .font(InkspringTypography.editorial(48, relativeTo: .largeTitle))
877 .accessibilityAddTraits(.isHeader)
878 Text("Your private studio for research and writing.")
879 .font(InkspringTypography.interface(15))
880 .foregroundStyle(palette.muted)
881 }
882 }
883 if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
884 let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—"
885 Text("Version \(version) (\(build))")
886 .font(InkspringTypography.interface(12).weight(.medium))
887 .foregroundStyle(palette.muted)
888 }
889 }
890 .frame(maxWidth: .infinity, alignment: .leading)
891 .padding(25)
892 .studioSurface(22, fill: palette.panel)
893 }
894
895 private var siteLinks: some View {
896 HStack(spacing: 12) {
897 ProtomotaProductPill()
898 projectLinks
899 }
900 }
901
902 private var projectLinks: some View {
903 HStack(spacing: 8) {
904 Link(destination: URL(string: "https://inkspring.ai/")!) {
905 StudioLinkOutLabel { Label("Inkspring website", systemImage: "globe") }
906 }
907 Link(destination: URL(string: "https://github.com/projectatomai/inkspring")!) {
908 StudioLinkOutLabel { Label("View source on GitHub", systemImage: "chevron.left.forwardslash.chevron.right") }
909 }
910 }
911 }
912
913 private var copyright: some View { InkspringCopyright() }
914}
915
916private struct InkspringBrandIcon: View {
917 @Environment(\.studioPalette) private var palette
918 let width: CGFloat
919 let height: CGFloat
920 let radius: CGFloat
921
922 var body: some View {
923 if let icon = NSApplication.shared.applicationIconImage {
924 Image(nsImage: icon)
925 .renderingMode(.original)
926 .resizable()
927 .scaledToFill()
928 .frame(width: width, height: height)
929 .clipShape(.rect(cornerRadius: radius))
930 .shadow(color: palette.dark ? .white.opacity(0.14) : .black.opacity(0.18),
931 radius: palette.dark ? 10 : 8, x: 0, y: palette.dark ? 0 : 4)
932 .accessibilityHidden(true)
933 }
934 }
935}
936
937private struct ProtomotaProductPill: View {
938 var body: some View {
939 Link(destination: URL(string: "https://projectatom.ai/")!) {
940 HStack(spacing: 8) {
941 if let url = Bundle.main.url(forResource: "project-atom-logo", withExtension: "png"),
942 let logo = NSImage(contentsOf: url) {
943 Image(nsImage: logo)
944 .renderingMode(.original)
945 .resizable()
946 .scaledToFit()
947 .frame(width: 22, height: 22)
948 .clipShape(.rect(cornerRadius: 6))
949 .accessibilityHidden(true)
950 }
951 Text("A Project ATOM app")
952 .font(InkspringTypography.interface(13).weight(.semibold))
953 .lineLimit(1)
954 Image(systemName: "arrow.up.right")
955 .font(.caption.weight(.medium))
956 .accessibilityHidden(true)
957 }
958 .fixedSize()
959 .padding(.leading, 10)
960 .padding(.trailing, 16)
961 .padding(.vertical, 9)
962 .foregroundStyle(.white)
963 .background(.black, in: Capsule())
964 .overlay { Capsule().strokeBorder(.white.opacity(0.14)) }
965 .contentShape(Capsule())
966 }
967 .buttonStyle(.plain)
968 .help("Visit projectatom.ai")
969 }
970}
971
972private struct InkspringCopyright: View {
973 @Environment(\.studioPalette) private var palette
974
975 var body: some View {
976 Text("A Project ATOM project")
977 .font(InkspringTypography.interface(12))
978 .foregroundStyle(palette.muted)
979 }
980}
981
982private struct InkspringSupport: View {
983 @Environment(\.studioPalette) private var palette
984
985 var body: some View {
986 VStack(alignment: .leading, spacing: 16) {
987 HStack(spacing: 16) {
988 InkspringBrandIcon(width: 66, height: 58, radius: 15)
989 VStack(alignment: .leading, spacing: 4) {
990 Text("Inkspring")
991 .font(InkspringTypography.editorial(30, relativeTo: .title2))
992 .accessibilityAddTraits(.isHeader)
993 Text("A private studio for research and writing.")
994 .font(InkspringTypography.interface(13))
995 .foregroundStyle(palette.muted)
996 .fixedSize(horizontal: false, vertical: true)
997 }
998 }
999 .frame(maxWidth: .infinity, alignment: .leading)
1000 .padding(18)
1001 .studioSurface(18, fill: palette.panel)
1002
1003 InkspringSupportButton()
1004 InkspringSupportCards()
1005
1006 StudioRule()
1007 ViewThatFits(in: .horizontal) {
1008 HStack {
1009 ProtomotaProductPill()
1010 Spacer(minLength: 12)
1011 InkspringCopyright().fixedSize()
1012 }
1013 VStack(alignment: .leading, spacing: 10) {
1014 ProtomotaProductPill()
1015 InkspringCopyright()
1016 }
1017 }
1018 }
1019 }
1020}
1021
1022private struct InkspringSupportCards: View {
1023 @Environment(\.studioPalette) private var palette
1024 @Environment(\.openURL) private var openURL
1025
1026 var body: some View {
1027 VStack(alignment: .leading, spacing: 16) {
1028 Link(destination: InkspringCommunity.support) {
1029 StudioLinkOutLabel { Label("Get App Help", systemImage: "questionmark.circle") }
1030 }
1031 Link(destination: InkspringCommunity.websiteHelp) {
1032 StudioLinkOutLabel { Label("Setup and Troubleshooting", systemImage: "book") }
1033 }
1034 Text("Get personal help with Inkspring on Mac, iPhone, and iPad, including desktop setup, iCloud sync, and MCP connections.")
1035 .font(.callout)
1036 .foregroundStyle(palette.muted)
1037 communityCards
1038 }
1039 }
1040
1041 private var communityCards: some View {
1042 SupportCardLayout {
1043 card("Feedback", detail: "Tell us what works and what could be better.",
1044 symbol: "bubble.left.and.bubble.right", action: "Send Feedback", url: InkspringCommunity.feedback, tracked: .feedback)
1045 card("Glimmer community", detail: "Connect with other people using Project ATOM apps.",
1046 symbol: "person.2", action: "Explore the community", url: InkspringCommunity.community, tracked: .newsletter)
1047 }
1048 }
1049
1050 private func card(_ title: String, detail: String, symbol: String, action: String, url: URL,
1051 tracked: InkspringSupportReminder.Action? = nil) -> some View {
1052 VStack(alignment: .leading, spacing: 10) {
1053 Image(systemName: symbol)
1054 .font(.system(size: 16, weight: .medium))
1055 .foregroundStyle(palette.iconAccent)
1056 .frame(width: 36, height: 36)
1057 .background(palette.well, in: .rect(cornerRadius: 11))
1058 .accessibilityHidden(true)
1059 Text(title)
1060 .font(InkspringTypography.interface(14).weight(.semibold))
1061 .accessibilityAddTraits(.isHeader)
1062 Text(detail)
1063 .font(InkspringTypography.interface(13))
1064 .foregroundStyle(palette.muted)
1065 .fixedSize(horizontal: false, vertical: true)
1066 Spacer(minLength: 2)
1067 Button {
1068 if let tracked { InkspringSupportReminder.record(tracked) }
1069 openURL(url)
1070 } label: {
1071 StudioLinkOutLabel { Text(action) }
1072 }
1073 }
1074 .padding(16)
1075 .frame(maxWidth: .infinity, minHeight: 172, maxHeight: .infinity, alignment: .topLeading)
1076 .studioSurface(18)
1077 }
1078}
1079
1080private struct InkspringSupportButton: View {
1081 @Environment(\.studioPalette) private var palette
1082 @State private var isPresented = false
1083
1084 var body: some View {
1085 Button("Share or send feedback", systemImage: "heart") { isPresented = true }
1086 .sheet(isPresented: $isPresented) {
1087 InkspringSupportSheet(isReminder: false)
1088 .studioAppearance(palette)
1089 }
1090 }
1091}
1092
1093struct InkspringSupportSheet: View {
1094 let isReminder: Bool
1095 @Environment(\.studioPalette) private var palette
1096 @Environment(\.openURL) private var openURL
1097 @Environment(\.dismiss) private var dismiss
1098 @AppStorage(InkspringSupportReminder.actionsKey) private var clicks = ""
1099 @State private var sharePicker = InkspringSupportSharePicker()
1100
1101 var body: some View {
1102 VStack(alignment: .leading, spacing: 16) {
1103 HStack(spacing: 16) {
1104 InkspringBrandIcon(width: 66, height: 58, radius: 15)
1105 VStack(alignment: .leading, spacing: 4) {
1106 Text("Free software.\nSupported by people.")
1107 .font(InkspringTypography.editorial(26, relativeTo: .title2))
1108 .accessibilityAddTraits(.isHeader)
1109 Text("Help more people discover Inkspring and tell us what we can improve.")
1110 .foregroundStyle(palette.muted)
1111 }
1112 }
1113 VStack(spacing: 8) {
1114 Button { visit(.feedback, url: InkspringCommunity.feedback) } label: {
1115 row("Send feedback", detail: "Tell us what’s working and what could be better",
1116 symbol: "bubble.left.and.bubble.right", action: .feedback)
1117 }
1118 Button {
1119 sharePicker.show {
1120 if InkspringSupportReminder.record(.share), isReminder { dismiss() }
1121 }
1122 } label: {
1123 row("Share Inkspring", detail: "Send someone a link to the app",
1124 symbol: "square.and.arrow.up", action: .share)
1125 }
1126 .background(InkspringShareAnchor(view: sharePicker.anchor).allowsHitTesting(false))
1127 Button { visit(.support, url: InkspringCommunity.support) } label: {
1128 row("Open a Support Ticket", detail: "Get help or follow replies for Mac, iPhone, and iPad",
1129 symbol: "headphones", action: .support)
1130 }
1131 Button { visit(.apps, url: InkspringCommunity.apps) } label: {
1132 row("More Free Apps from Project ATOM", detail: "Explore more free apps from Project ATOM",
1133 symbol: "arrow.up.forward.app", action: .apps)
1134 }
1135 }
1136 .buttonStyle(SupportActionRowStyle())
1137 Text("Checkmarks show which buttons you’ve opened.")
1138 .font(.caption)
1139 .foregroundStyle(palette.muted)
1140 StudioRule()
1141 HStack(spacing: 14) {
1142 if isReminder {
1143 Button("Don’t show again") {
1144 InkspringSupportReminder.dismissPermanently()
1145 dismiss()
1146 }
1147 .buttonStyle(.plain)
1148 .font(InkspringTypography.interface(12))
1149 .foregroundStyle(palette.muted)
1150 .accessibilityIdentifier("supportReminder.dontShowAgain")
1151 }
1152 Spacer()
1153 Button(isReminder ? "Later" : "Done") { dismiss() }
1154 .buttonStyle(StudioActionStyle(prominent: isReminder))
1155 .keyboardShortcut(.cancelAction)
1156 .accessibilityIdentifier(isReminder ? "supportReminder.later" : "supportSheet.done")
1157 }
1158 }
1159 .padding(24)
1160 .frame(width: 500)
1161 .background(palette.canvas)
1162 }
1163
1164 private func visit(_ action: InkspringSupportReminder.Action, url: URL) {
1165 let finished = InkspringSupportReminder.record(action)
1166 openURL(url)
1167 if finished, isReminder { dismiss() }
1168 }
1169
1170 private func row(_ title: String, detail: String, symbol: String,
1171 action: InkspringSupportReminder.Action) -> some View {
1172 let clicked = InkspringSupportReminder.clicked(clicks).contains(action)
1173 return HStack(spacing: 12) {
1174 Image(systemName: symbol)
1175 .frame(width: 22)
1176 .foregroundStyle(palette.iconAccent)
1177 .accessibilityHidden(true)
1178 VStack(alignment: .leading, spacing: 3) {
1179 Text(title).font(.callout.weight(.semibold))
1180 Text(detail).font(.caption).foregroundStyle(palette.muted)
1181 }
1182 Spacer(minLength: 8)
1183 Image(systemName: clicked ? "checkmark.circle.fill" : "arrow.up.right")
1184 .foregroundStyle(palette.iconAccent)
1185 .accessibilityLabel(clicked ? "Previously opened" : "Open")
1186 }
1187 .padding(12)
1188 .contentShape(.rect(cornerRadius: 12))
1189 .accessibilityElement(children: .combine)
1190 }
1191}
1192
1193private struct SupportActionRowStyle: ButtonStyle {
1194 @Environment(\.studioPalette) private var palette
1195
1196 func makeBody(configuration: Configuration) -> some View {
1197 if palette.theme == .paper {
1198 configuration.label.studioPaperControl(in: RoundedRectangle(cornerRadius: 12),
1199 fill: configuration.isPressed ? palette.hover : palette.control)
1200 } else {
1201 configuration.label.studioSurface(12, fill: configuration.isPressed ? palette.hover : palette.card)
1202 }
1203 }
1204}
1205
1206private struct InkspringShareAnchor: NSViewRepresentable {
1207 let view: NSView
1208 func makeNSView(context: Context) -> NSView { view }
1209 func updateNSView(_ nsView: NSView, context: Context) {}
1210}
1211
1212@MainActor
1213private final class InkspringSupportSharePicker: NSObject, NSSharingServicePickerDelegate {
1214 let anchor = NSView()
1215 private var picker: NSSharingServicePicker?
1216 private var finished: (() -> Void)?
1217
1218 func show(finished: @escaping () -> Void) {
1219 guard picker == nil, anchor.window != nil else { return }
1220 let picker = NSSharingServicePicker(items: [InkspringCommunity.website])
1221 self.picker = picker
1222 self.finished = finished
1223 picker.delegate = self
1224 picker.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .minY)
1225 }
1226
1227 nonisolated func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, didChoose service: NSSharingService?) {
1228 Task { @MainActor in self.complete() }
1229 }
1230
1231 private func complete() {
1232 let completion = finished
1233 finished = nil
1234 picker = nil
1235 completion?()
1236 }
1237}
1238
1239private struct SupportCardLayout: Layout {
1240 private let gap: CGFloat = 14
1241 private let minimumCardWidth: CGFloat = 190
1242
1243 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
1244 let width = proposal.width ?? 3 * minimumCardWidth + 2 * gap
1245 let metrics = measure(width: width, subviews: subviews)
1246 let rows = metrics.inRow ? 1 : subviews.count
1247 return CGSize(width: width, height: metrics.height * CGFloat(rows) + gap * CGFloat(max(0, rows - 1)))
1248 }
1249
1250 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
1251 let metrics = measure(width: bounds.width, subviews: subviews)
1252 for (index, card) in subviews.enumerated() {
1253 let x = metrics.inRow ? CGFloat(index) * (metrics.width + gap) : 0
1254 let y = metrics.inRow ? 0 : CGFloat(index) * (metrics.height + gap)
1255 card.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading,
1256 proposal: ProposedViewSize(width: metrics.width, height: metrics.height))
1257 }
1258 }
1259
1260 private func measure(width: CGFloat, subviews: Subviews) -> (width: CGFloat, height: CGFloat, inRow: Bool) {
1261 let count = CGFloat(subviews.count)
1262 let gutters = gap * max(0, count - 1)
1263 let inRow = width >= minimumCardWidth * count + gutters
1264 let cardWidth = inRow ? (width - gutters) / max(1, count) : width
1265 let height = subviews.map { $0.sizeThatFits(ProposedViewSize(width: cardWidth, height: nil)).height }.max() ?? 0
1266 return (cardWidth, height, inRow)
1267 }
1268}
1269
1270struct BackupControls: View {
1271 let workspace: Workspace
1272 @State private var backgroundStatus: SMAppService.Status = .notRegistered
1273 @State private var backingUp = false
1274 @State private var cloudStatus: ICloudBackup.UploadStatus?
1275
1276 private var dailyEnabled: Bool { workspace.settings[DailyBackup.enabledKey] as? Bool == true }
1277 private var folder: String { workspace.settings[DailyBackup.folderKey] as? String ?? "" }
1278 private var lastError: String { workspace.settings[DailyBackup.lastErrorKey] as? String ?? "" }
1279 private var lastBackupPath: String { workspace.settings[DailyBackup.lastFileKey] as? String ?? "" }
1280
1281 var body: some View {
1282 VStack(alignment: .leading, spacing: 15) {
1283 manual
1284 daily
1285 }
1286 .onAppear(perform: refreshStatus)
1287 .onChange(of: workspace.settings[DailyBackup.registrationKey] as? String) { _, _ in refreshStatus() }
1288 .task(id: lastBackupPath) { await checkCloudStatus(path: lastBackupPath) }
1289 .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
1290 refreshStatus()
1291 Task { await workspace.checkDailyBackup() }
1292 }
1293 }
1294
1295 private var manual: some View {
1296 GroupBox("Workspace backup") {
1297 VStack(alignment: .leading, spacing: 12) {
1298 Text("Save your projects, writing, research, and local media in a ZIP. Restore it on any Mac running Inkspring.")
1299 HStack {
1300 Button("Export Backup…", systemImage: "square.and.arrow.up") { workspace.exportBackup() }
1301 Button("Import / Restore…", systemImage: "square.and.arrow.down") {
1302 Task { await workspace.restoreBackup() }
1303 }
1304 .disabled(workspace.restoringBackup || workspace.importingWorkspaceFolder)
1305 if workspace.restoringBackup { ProgressView().controlSize(.small).accessibilityLabel("Preparing backup restore") }
1306 }
1307 HStack {
1308 Button("Import Workspace Folder…", systemImage: "folder") {
1309 Task { await workspace.importWorkspaceFolder() }
1310 }
1311 .disabled(workspace.importingWorkspaceFolder || workspace.restoringBackup)
1312 if workspace.importingWorkspaceFolder {
1313 ProgressView().controlSize(.small).accessibilityLabel("Preparing workspace import")
1314 }
1315 }
1316 }
1317 .frame(maxWidth: .infinity, alignment: .leading)
1318 .padding(5)
1319 }
1320 }
1321
1322 private var daily: some View {
1323 GroupBox("Daily backups") {
1324 VStack(alignment: .leading, spacing: 10) {
1325 Toggle("Back up once a day", isOn: Binding(get: { dailyEnabled }, set: {
1326 workspace.setDailyBackupEnabled($0)
1327 refreshStatus()
1328 }))
1329 .disabled(folder.isEmpty)
1330 HStack {
1331 Text(folder.isEmpty ? "Choose where to save daily ZIP files." : folder)
1332 .foregroundStyle(.secondary)
1333 .textSelection(.enabled)
1334 Spacer()
1335 Button("Choose folder…") { workspace.chooseDailyBackupFolder() }
1336 }
1337 if FileManager.default.fileExists(atPath: ICloudBackup.drive.path) {
1338 Button("Choose iCloud Drive…", systemImage: "icloud") {
1339 workspace.chooseDailyBackupFolder(startingAt: ICloudBackup.drive)
1340 }
1341 }
1342 if dailyEnabled && backgroundStatus == .enabled {
1343 Text("Runs at 3:00 a.m. while you’re signed in. Inkspring retries later if the backup folder was unavailable.")
1344 .font(.caption)
1345 .foregroundStyle(.secondary)
1346 } else if dailyEnabled {
1347 Text("Inkspring checks for a daily backup while it’s open. Allow Inkspring in Login Items to run backups while it’s closed.")
1348 .font(.caption)
1349 .foregroundStyle(.secondary)
1350 if !DailyBackup.usesTestWorkspace {
1351 Button("Open Login Items…") { SMAppService.openSystemSettingsLoginItems() }
1352 }
1353 }
1354 HStack {
1355 Button("Back Up Now", systemImage: "arrow.clockwise") {
1356 backingUp = true
1357 Task {
1358 await workspace.checkDailyBackup(requested: true)
1359 backingUp = false
1360 }
1361 }
1362 .disabled(folder.isEmpty || backingUp)
1363 if backingUp { ProgressView().controlSize(.small) }
1364 }
1365 if let value = workspace.settings[DailyBackup.lastSuccessKey] as? String,
1366 let date = scheduleDate(value) {
1367 HStack {
1368 Text("Last backup \(date.formatted(date: .abbreviated, time: .shortened))")
1369 if !lastBackupPath.isEmpty {
1370 Button("Show in Finder") {
1371 NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: lastBackupPath)])
1372 }
1373 }
1374 }
1375 .font(.callout)
1376 }
1377 if let cloudStatus { uploadLabel(cloudStatus) }
1378 if !lastError.isEmpty {
1379 Label(lastError, systemImage: "exclamationmark.triangle").foregroundStyle(.red)
1380 }
1381 if dailyEnabled, let error = workspace.backupRegistrationError {
1382 Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red)
1383 }
1384 }
1385 .frame(maxWidth: .infinity, alignment: .leading)
1386 .padding(5)
1387 }
1388 }
1389
1390 private func refreshStatus() {
1391 guard !DailyBackup.usesTestWorkspace else { return }
1392 backgroundStatus = DailyBackup.service.status
1393 }
1394
1395 private func checkCloudStatus(path: String) async {
1396 cloudStatus = nil
1397 guard !path.isEmpty else { return }
1398 let file = URL(fileURLWithPath: path)
1399 while !Task.isCancelled {
1400 let status = await Task.detached(priority: .utility) { ICloudBackup.uploadStatus(of: file) }.value
1401 guard !Task.isCancelled else { return }
1402 cloudStatus = status
1403 if status == nil { return }
1404 try? await Task.sleep(for: .seconds(5))
1405 }
1406 }
1407
1408 @ViewBuilder private func uploadLabel(_ status: ICloudBackup.UploadStatus) -> some View {
1409 switch status {
1410 case .uploaded:
1411 Label("Uploaded to iCloud Drive", systemImage: "checkmark.icloud").foregroundStyle(.secondary)
1412 case .waiting:
1413 Label("Waiting for iCloud Drive to upload", systemImage: "icloud.and.arrow.up").foregroundStyle(.secondary)
1414 case .unavailable:
1415 Label("The iCloud Drive backup is unavailable", systemImage: "exclamationmark.icloud").foregroundStyle(.secondary)
1416 case .excluded:
1417 Label("This ZIP is excluded from iCloud sync", systemImage: "exclamationmark.icloud").foregroundStyle(.secondary)
1418 case let .failed(message):
1419 Label(message, systemImage: "exclamationmark.icloud").foregroundStyle(.red)
1420 }
1421 }
1422}
1423
1424
1425private struct DeveloperConnectionSettings: View {
1426 let workspace: Workspace
1427 let platform: SocialPlatform
1428 let showsConnectButton: Bool
1429 @State private var clientID = ""
1430 @State private var clientSecret = ""
1431 @State private var pages = false
1432 @State private var expanded = false
1433
1434 private var accounts: ManagedSocialAccounts { workspace.socialAccounts }
1435
1436 init(workspace: Workspace, platform: SocialPlatform, initiallyExpanded: Bool = false, showsConnectButton: Bool = true) {
1437 self.workspace = workspace
1438 self.platform = platform
1439 self.showsConnectButton = showsConnectButton
1440 _expanded = State(initialValue: initiallyExpanded)
1441 }
1442
1443 var body: some View {
1444 VStack(alignment: .leading, spacing: 8) {
1445 if platform == .linkedin {
1446 if accounts.connecting == .linkedin {
1447 Text("Finish signing in on LinkedIn. Click Allow if asked, then choose Return to Inkspring.")
1448 .font(.callout)
1449 .foregroundStyle(.secondary)
1450 }
1451 SetupHelpLink("LinkedIn setup guide", topic: "connect-linkedin")
1452 }
1453 DisclosureGroup(platform == .linkedin ? "LinkedIn developer app credentials" : "Use your own developer app",
1454 isExpanded: $expanded) {
1455 developerAppFields
1456 .padding(.top, 7)
1457 }
1458 }
1459 .onChange(of: expanded, initial: true) { _, open in
1460 if open {
1461 clientID = accounts.developerAppIDs[platform] ?? ""
1462 pages = platform == .linkedin && accounts.developerPages
1463 } else {
1464 clientSecret = ""
1465 }
1466 }
1467 .onChange(of: accounts.developerAppIDs[platform]) { old, new in
1468 if expanded && (clientID.isEmpty || clientID == old) {
1469 clientID = new ?? ""
1470 pages = platform == .linkedin && accounts.developerPages
1471 }
1472 }
1473 }
1474
1475 private var developerAppFields: some View {
1476 VStack(alignment: .leading, spacing: 8) {
1477 if platform == .linkedin {
1478 Text("Your Client ID and secret identify your developer app. You’ll approve access to your profile separately on LinkedIn.")
1479 .font(.callout)
1480 .foregroundStyle(.secondary)
1481 StudioExternalLink("Open LinkedIn My Apps", destination: platform.developerConsole)
1482 } else {
1483 SetupHelpLink("\(platform.name) setup and troubleshooting", topic: "connect-" + platform.rawValue)
1484 }
1485 LabeledContent("Authorized redirect URL") {
1486 Text(platform.developerCallback.absoluteString).textSelection(.enabled)
1487 Button("Copy") { copy(platform.developerCallback.absoluteString) }
1488 }
1489 TextField(platform == .tiktok ? "Client key" : "Client ID", text: $clientID)
1490 .studioInput()
1491 if platform != .reddit {
1492 SecureField(platform.needsClientSecret ? "Client secret" : "Client secret (optional)", text: $clientSecret)
1493 .studioInput()
1494 }
1495 if platform == .linkedin {
1496 Toggle("Request company Page access", isOn: $pages)
1497 .help("Requires LinkedIn Community Management approval and a role on the Page.")
1498 Text("For a personal profile, leave company Page access off.")
1499 .font(.caption)
1500 .foregroundStyle(.secondary)
1501 }
1502 HStack {
1503 Button("Save developer app") {
1504 workspace.perform {
1505 try accounts.saveDeveloperApp(platform, input: DeveloperOAuthConfiguration(
1506 clientID: clientID, clientSecret: clientSecret, linkedInPages: pages
1507 ))
1508 clientSecret = ""
1509 workspace.notice = "Developer app saved"
1510 }
1511 }
1512 .disabled(clientID.isEmpty || accounts.connecting != nil)
1513 if showsConnectButton {
1514 Button(platform == .linkedin ? "Connect LinkedIn with this app…" : "Connect developer app…") {
1515 Task {
1516 do { try await accounts.connect(platform, developerApp: true) }
1517 catch is CancellationError {}
1518 catch { workspace.error = error.localizedDescription }
1519 }
1520 }
1521 .disabled(accounts.developerAppIDs[platform] == nil || accounts.connecting != nil)
1522 }
1523 }
1524 }
1525 }
1526}