TitleOptimizerView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import SwiftUI
  2. struct TitleOptimizerView: View {
  3. @Environment(\.requirePremiumAccess) private var requirePremiumAccess
  4. @Bindable var viewModel: TitleOptimizerViewModel
  5. private enum Layout {
  6. static let horizontalPadding: CGFloat = 24
  7. static let columnWidth: CGFloat = 300
  8. static let columnSpacing: CGFloat = 20
  9. static let sectionSpacing: CGFloat = 12
  10. }
  11. var body: some View {
  12. VStack(spacing: 0) {
  13. header
  14. messageBanners
  15. ScrollViewReader { scrollProxy in
  16. ScrollView {
  17. VStack(alignment: .leading, spacing: 12) {
  18. tabBar
  19. PostPageBoundary {
  20. switch viewModel.selectedTab {
  21. case .optimize:
  22. optimizeContent
  23. case .compare:
  24. compareContent
  25. case .preview:
  26. previewContent
  27. }
  28. }
  29. }
  30. .padding(.horizontal, Layout.horizontalPadding)
  31. .padding(.top, 12)
  32. .padding(.bottom, 24)
  33. }
  34. .onChange(of: viewModel.variants.count) { _, count in
  35. guard count > 0, viewModel.selectedTab == .optimize else { return }
  36. withAnimation(.easeInOut(duration: 0.25)) {
  37. scrollProxy.scrollTo("title-suggestions", anchor: .top)
  38. }
  39. }
  40. }
  41. }
  42. .background(AppTheme.background)
  43. }
  44. // MARK: - Header
  45. private var header: some View {
  46. HStack(spacing: 14) {
  47. ModernSidebarIconView(kind: .titleOptimizer, size: 40)
  48. VStack(alignment: .leading, spacing: 2) {
  49. Text("Title Optimizer")
  50. .font(.system(size: 18, weight: .semibold))
  51. .foregroundStyle(AppTheme.textPrimary)
  52. Text(viewModel.usesLiveAI ? "Craft viral Reddit titles with OpenAI" : "Craft viral Reddit titles with AI templates")
  53. .font(.system(size: 11))
  54. .foregroundStyle(AppTheme.textSecondary)
  55. }
  56. Spacer()
  57. headerActions
  58. }
  59. .padding(.horizontal, Layout.horizontalPadding)
  60. .padding(.vertical, 16)
  61. .overlay(alignment: .bottom) {
  62. Rectangle()
  63. .fill(AppTheme.border)
  64. .frame(height: 1)
  65. }
  66. }
  67. @ViewBuilder
  68. private var messageBanners: some View {
  69. if let error = viewModel.errorMessage {
  70. PostGeneratorMessageBanner(message: error, isError: true)
  71. .padding(.horizontal, Layout.horizontalPadding)
  72. .padding(.top, 8)
  73. } else if let success = viewModel.successMessage {
  74. PostGeneratorMessageBanner(message: success, isError: false)
  75. .padding(.horizontal, Layout.horizontalPadding)
  76. .padding(.top, 8)
  77. }
  78. }
  79. private var headerActions: some View {
  80. HStack(spacing: 8) {
  81. Button {
  82. viewModel.resetDraft()
  83. } label: {
  84. Label("Reset", systemImage: "arrow.counterclockwise")
  85. .font(.system(size: 11, weight: .medium))
  86. }
  87. .buttonStyle(AppSecondaryButtonStyle())
  88. Button {
  89. viewModel.copyToClipboard()
  90. } label: {
  91. Label("Copy", systemImage: "doc.on.doc")
  92. .font(.system(size: 11, weight: .medium))
  93. }
  94. .buttonStyle(AppSecondaryButtonStyle())
  95. .disabled(viewModel.activeTitle.trimmingCharacters(in: .whitespaces).isEmpty)
  96. Button {
  97. guard requirePremiumAccess() else {
  98. viewModel.errorMessage = "Premium is required to generate AI title suggestions."
  99. return
  100. }
  101. Task { await viewModel.optimizeTitles() }
  102. } label: {
  103. HStack(spacing: 6) {
  104. if viewModel.isOptimizing {
  105. ProgressView()
  106. .controlSize(.small)
  107. .tint(.white)
  108. } else {
  109. Image(systemName: "sparkles")
  110. .font(.system(size: 11, weight: .semibold))
  111. }
  112. Text(viewModel.isOptimizing ? "Optimizing…" : "Optimize")
  113. .font(.system(size: 11, weight: .semibold))
  114. }
  115. .foregroundStyle(.white)
  116. .padding(.horizontal, 14)
  117. .padding(.vertical, 8)
  118. .background(viewModel.canOptimize ? AppTheme.accentBlue : AppTheme.accentBlue.opacity(0.4))
  119. .clipShape(RoundedRectangle(cornerRadius: 8))
  120. }
  121. .buttonStyle(AppPrimaryButtonStyle())
  122. .disabled(viewModel.isOptimizing)
  123. }
  124. }
  125. // MARK: - Tab Bar
  126. private var tabBar: some View {
  127. ToolSegmentedTabBar(
  128. selection: $viewModel.selectedTab,
  129. accentColor: AppTheme.accentBlue,
  130. width: 300
  131. )
  132. }
  133. // MARK: - Optimize
  134. private var optimizeContent: some View {
  135. optimizeColumns
  136. }
  137. private var optimizeColumns: some View {
  138. HStack(alignment: .top, spacing: Layout.columnSpacing) {
  139. optimizeColumn(title: "Configuration", icon: "slider.horizontal.3") {
  140. configurationPanel
  141. }
  142. .frame(width: Layout.columnWidth)
  143. .layoutPriority(1)
  144. Rectangle()
  145. .fill(AppTheme.border)
  146. .frame(width: 1)
  147. .padding(.vertical, 2)
  148. optimizeColumn(title: "Title & Suggestions", icon: "textformat") {
  149. editorPanel
  150. }
  151. .frame(minWidth: 0, maxWidth: .infinity)
  152. .layoutPriority(0)
  153. }
  154. }
  155. private func optimizeColumn<Content: View>(
  156. title: String,
  157. icon: String,
  158. @ViewBuilder content: () -> Content
  159. ) -> some View {
  160. VStack(alignment: .leading, spacing: Layout.sectionSpacing) {
  161. sectionHeader(title: title, icon: icon)
  162. content()
  163. }
  164. }
  165. private func sectionHeader(title: String, icon: String) -> some View {
  166. HStack(spacing: 6) {
  167. Image(systemName: icon)
  168. .font(.system(size: 10, weight: .semibold))
  169. .foregroundStyle(AppTheme.accentBlue)
  170. Text(title)
  171. .font(.system(size: 11, weight: .semibold))
  172. .foregroundStyle(AppTheme.textSecondary)
  173. }
  174. .textCase(.uppercase)
  175. .tracking(0.4)
  176. }
  177. private var configurationPanel: some View {
  178. VStack(spacing: Layout.sectionSpacing) {
  179. PostFormCard(title: "Target Subreddit", subtitle: "Tailor titles for the community") {
  180. PostFormField(
  181. label: "Subreddit",
  182. placeholder: "technology",
  183. text: $viewModel.draft.subreddit,
  184. prefix: "r/"
  185. )
  186. }
  187. PostFormCard(title: "AI Settings", subtitle: "Guide topic, tone, and style") {
  188. VStack(alignment: .leading, spacing: 12) {
  189. PostFormField(
  190. label: "Topic / Keywords",
  191. placeholder: "e.g. macOS productivity tips",
  192. text: $viewModel.draft.topic
  193. )
  194. VStack(alignment: .leading, spacing: 6) {
  195. Text("Tone")
  196. .font(.system(size: 10, weight: .medium))
  197. .foregroundStyle(AppTheme.textTertiary)
  198. TonePicker(selectedTone: $viewModel.draft.tone)
  199. }
  200. }
  201. }
  202. PostFormCard(title: "Title Goal", subtitle: "What kind of hook do you want?") {
  203. TitleGoalPicker(selectedGoal: $viewModel.draft.titleGoal)
  204. }
  205. PostFormCard(title: "Preview Context", subtitle: "Optional — affects preview style") {
  206. VStack(alignment: .leading, spacing: 12) {
  207. PostTypePicker(selectedType: Binding(
  208. get: { viewModel.draft.postType },
  209. set: { viewModel.selectPostType($0) }
  210. ))
  211. HStack(spacing: 8) {
  212. PostTagToggle(
  213. title: "NSFW",
  214. systemImage: "exclamationmark.triangle.fill",
  215. activeColor: Color(hex: 0xEF4444),
  216. isOn: $viewModel.draft.isNSFW
  217. )
  218. .frame(maxWidth: .infinity)
  219. PostTagToggle(
  220. title: "Spoiler",
  221. systemImage: "eye.slash.fill",
  222. activeColor: AppTheme.textSecondary,
  223. isOn: $viewModel.draft.isSpoiler
  224. )
  225. .frame(maxWidth: .infinity)
  226. PostTagToggle(
  227. title: "OC",
  228. systemImage: "star.fill",
  229. activeColor: AppTheme.accentGreen,
  230. isOn: $viewModel.draft.isOC
  231. )
  232. .frame(maxWidth: .infinity)
  233. }
  234. PostFormField(
  235. label: "Flair",
  236. placeholder: "Discussion, Question, Meme…",
  237. text: $viewModel.draft.flair
  238. )
  239. }
  240. }
  241. PostFormCard(title: "Suggestions", subtitle: "How many variants to generate") {
  242. TitleVariantCountPicker(selectedCount: $viewModel.draft.variantCount)
  243. }
  244. }
  245. }
  246. private var editorPanel: some View {
  247. VStack(spacing: Layout.sectionSpacing) {
  248. PostFormCard(title: "Original Title", subtitle: "The title you want to improve") {
  249. PostFormField(
  250. label: "Post Title",
  251. placeholder: "Enter your draft title here",
  252. text: $viewModel.draft.originalTitle
  253. )
  254. }
  255. characterCountFooter
  256. if let analysis = viewModel.analysis {
  257. TitleAnalysisCard(analysis: analysis)
  258. }
  259. suggestionsSection
  260. .id("title-suggestions")
  261. }
  262. }
  263. @ViewBuilder
  264. private var suggestionsSection: some View {
  265. PostFormCard(
  266. title: "AI Suggestions",
  267. subtitle: viewModel.variants.isEmpty
  268. ? "Hit Optimize to generate title variants"
  269. : "\(viewModel.variants.count) optimized titles ranked by score"
  270. ) {
  271. if viewModel.variants.isEmpty {
  272. TitleOptimizerEmptyState(
  273. icon: "textformat.size",
  274. title: "No suggestions yet",
  275. subtitle: "Fill in your subreddit, topic, and title,\nthen tap Optimize to get AI-powered variants."
  276. )
  277. } else {
  278. VStack(spacing: 8) {
  279. ForEach(viewModel.variants) { variant in
  280. TitleVariantRow(
  281. variant: variant,
  282. isSelected: viewModel.selectedVariantID == variant.id,
  283. onSelect: { viewModel.selectVariant(variant) },
  284. onApply: { viewModel.applyVariant(variant) }
  285. )
  286. }
  287. }
  288. }
  289. }
  290. }
  291. private var characterCountFooter: some View {
  292. HStack(spacing: 12) {
  293. Text("\(viewModel.draft.originalTitle.count) / 300")
  294. .font(.system(size: 10, weight: .medium, design: .monospaced))
  295. .foregroundStyle(
  296. viewModel.draft.originalTitle.count > 300 ? Color(hex: 0xF87171) : AppTheme.textTertiary
  297. )
  298. Spacer()
  299. Text("Reddit limit: 300 characters for title")
  300. .font(.system(size: 10))
  301. .foregroundStyle(AppTheme.textTertiary)
  302. }
  303. .padding(.horizontal, 12)
  304. .padding(.vertical, 9)
  305. .background(
  306. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  307. .fill(AppTheme.cardBackground)
  308. .overlay(
  309. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  310. .stroke(AppTheme.cardBorder, lineWidth: 1)
  311. )
  312. )
  313. }
  314. // MARK: - Compare
  315. private var compareContent: some View {
  316. VStack(alignment: .leading, spacing: Layout.columnSpacing) {
  317. compareHeader
  318. if viewModel.variants.isEmpty {
  319. TitleOptimizerEmptyState(
  320. icon: "arrow.left.arrow.right",
  321. title: "Nothing to compare yet",
  322. subtitle: "Generate title suggestions on the Optimize tab first."
  323. )
  324. .frame(maxWidth: .infinity)
  325. } else {
  326. compareBody
  327. }
  328. }
  329. }
  330. private var compareBody: some View {
  331. VStack(spacing: Layout.sectionSpacing) {
  332. TitleCompareCard(
  333. title: viewModel.draft.originalTitle,
  334. score: viewModel.analysis?.overallScore,
  335. label: "Original",
  336. isOriginal: true,
  337. isSelected: viewModel.selectedVariantID == nil
  338. )
  339. HStack {
  340. Rectangle()
  341. .fill(AppTheme.border)
  342. .frame(height: 1)
  343. Text("vs")
  344. .font(.system(size: 10, weight: .semibold))
  345. .foregroundStyle(AppTheme.textTertiary)
  346. .padding(.horizontal, 8)
  347. Rectangle()
  348. .fill(AppTheme.border)
  349. .frame(height: 1)
  350. }
  351. VStack(spacing: 8) {
  352. ForEach(viewModel.variants) { variant in
  353. TitleCompareCard(
  354. title: variant.title,
  355. score: variant.score,
  356. label: "Variant #\(variantRank(variant))",
  357. isOriginal: false,
  358. isSelected: viewModel.selectedVariantID == variant.id
  359. )
  360. .onTapGesture {
  361. viewModel.selectVariant(variant)
  362. }
  363. }
  364. }
  365. compareMetadata
  366. }
  367. .frame(maxWidth: 640)
  368. .frame(maxWidth: .infinity)
  369. }
  370. private var compareHeader: some View {
  371. HStack(alignment: .top) {
  372. sectionHeader(title: "Side-by-Side Comparison", icon: "arrow.left.arrow.right")
  373. Spacer()
  374. if let best = viewModel.bestVariant {
  375. HStack(spacing: 6) {
  376. Image(systemName: "trophy.fill")
  377. .font(.system(size: 10))
  378. .foregroundStyle(AppTheme.accentYellow)
  379. Text("Best: \(best.score)/100")
  380. .font(.system(size: 10, weight: .semibold))
  381. .foregroundStyle(AppTheme.textSecondary)
  382. }
  383. .padding(.top, 1)
  384. }
  385. }
  386. }
  387. private var compareMetadata: some View {
  388. VStack(alignment: .leading, spacing: 0) {
  389. metadataRow(label: "Subreddit", value: viewModel.formattedSubreddit)
  390. metadataDivider
  391. metadataRow(label: "Goal", value: viewModel.draft.titleGoal.title)
  392. metadataDivider
  393. metadataRow(label: "Tone", value: viewModel.draft.tone.title)
  394. metadataDivider
  395. metadataRow(label: "Engine", value: viewModel.usesLiveAI ? "OpenAI" : "Local templates")
  396. metadataDivider
  397. metadataRow(label: "Active", value: viewModel.activeTitle)
  398. }
  399. .padding(14)
  400. .frame(maxWidth: .infinity, alignment: .leading)
  401. .background(
  402. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  403. .fill(AppTheme.cardBackground)
  404. .overlay(
  405. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  406. .stroke(AppTheme.cardBorder, lineWidth: 1)
  407. )
  408. )
  409. }
  410. private func variantRank(_ variant: TitleVariant) -> Int {
  411. (viewModel.variants.firstIndex(where: { $0.id == variant.id }) ?? 0) + 1
  412. }
  413. // MARK: - Preview
  414. private var previewContent: some View {
  415. VStack(alignment: .leading, spacing: Layout.columnSpacing) {
  416. sectionHeader(title: "Live Preview", icon: "eye")
  417. HStack {
  418. Spacer(minLength: 0)
  419. VStack(spacing: Layout.sectionSpacing) {
  420. RedditPostPreviewCard(
  421. draft: viewModel.previewDraft,
  422. formattedSubreddit: viewModel.formattedSubreddit
  423. )
  424. PostFormCard(title: "Feed Preview", subtitle: "How your title looks in a crowded feed") {
  425. VStack(spacing: 6) {
  426. TitleFeedPreviewRow(
  427. title: "Other trending post in this subreddit right now",
  428. subreddit: viewModel.formattedSubreddit
  429. )
  430. TitleFeedPreviewRow(
  431. title: viewModel.activeTitle,
  432. subreddit: viewModel.formattedSubreddit,
  433. isHighlighted: true
  434. )
  435. TitleFeedPreviewRow(
  436. title: "Another popular discussion happening nearby",
  437. subreddit: viewModel.formattedSubreddit
  438. )
  439. }
  440. }
  441. previewMetadata
  442. }
  443. .frame(maxWidth: 560)
  444. Spacer(minLength: 0)
  445. }
  446. }
  447. }
  448. private var previewMetadata: some View {
  449. VStack(alignment: .leading, spacing: 0) {
  450. metadataRow(label: "Active Title", value: viewModel.activeTitle)
  451. metadataDivider
  452. metadataRow(label: "Subreddit", value: viewModel.formattedSubreddit)
  453. metadataDivider
  454. metadataRow(label: "Goal", value: viewModel.draft.titleGoal.title)
  455. metadataDivider
  456. metadataRow(label: "Tone", value: viewModel.draft.tone.title)
  457. metadataDivider
  458. metadataRow(label: "Type", value: viewModel.draft.postType.title)
  459. metadataDivider
  460. metadataRow(label: "Engine", value: viewModel.usesLiveAI ? "OpenAI" : "Local templates")
  461. if let score = viewModel.analysis?.overallScore {
  462. metadataDivider
  463. metadataRow(label: "Score", value: "\(score)/100")
  464. }
  465. if viewModel.draft.isNSFW || viewModel.draft.isSpoiler || viewModel.draft.isOC {
  466. metadataDivider
  467. metadataRow(
  468. label: "Tags",
  469. value: [
  470. viewModel.draft.isNSFW ? "NSFW" : nil,
  471. viewModel.draft.isSpoiler ? "Spoiler" : nil,
  472. viewModel.draft.isOC ? "OC" : nil,
  473. ]
  474. .compactMap { $0 }
  475. .joined(separator: ", ")
  476. )
  477. }
  478. }
  479. .padding(14)
  480. .frame(maxWidth: .infinity, alignment: .leading)
  481. .background(
  482. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  483. .fill(AppTheme.cardBackground)
  484. .overlay(
  485. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  486. .stroke(AppTheme.cardBorder, lineWidth: 1)
  487. )
  488. )
  489. }
  490. private var metadataDivider: some View {
  491. Rectangle()
  492. .fill(AppTheme.border)
  493. .frame(height: 1)
  494. .padding(.vertical, 6)
  495. }
  496. private func metadataRow(label: String, value: String) -> some View {
  497. HStack(alignment: .top, spacing: 12) {
  498. Text(label)
  499. .font(.system(size: 10, weight: .medium))
  500. .foregroundStyle(AppTheme.textTertiary)
  501. .frame(width: 72, alignment: .leading)
  502. Text(value)
  503. .font(.system(size: 10))
  504. .foregroundStyle(AppTheme.textSecondary)
  505. .fixedSize(horizontal: false, vertical: true)
  506. }
  507. }
  508. }
  509. private struct TitleSecondaryButtonStyle: ButtonStyle {
  510. func makeBody(configuration: Configuration) -> some View {
  511. AppSecondaryButtonStyle().makeBody(configuration: configuration)
  512. }
  513. }
  514. #Preview {
  515. TitleOptimizerView(viewModel: TitleOptimizerViewModel())
  516. .frame(width: 880, height: 720)
  517. }