TitleOptimizerView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. HStack(spacing: 0) {
  128. ForEach(TitleOptimizerTab.allCases) { tab in
  129. Button {
  130. withAnimation(.easeInOut(duration: 0.15)) {
  131. viewModel.selectedTab = tab
  132. }
  133. } label: {
  134. Text(tab.title)
  135. .font(.system(size: 11, weight: .semibold))
  136. .foregroundStyle(viewModel.selectedTab == tab ? AppTheme.textPrimary : AppTheme.textSecondary)
  137. .frame(maxWidth: .infinity)
  138. .padding(.vertical, 7)
  139. .background(
  140. viewModel.selectedTab == tab
  141. ? AppTheme.cardBackground
  142. : Color.clear
  143. )
  144. .clipShape(RoundedRectangle(cornerRadius: 7))
  145. }
  146. .buttonStyle(AppPlainButtonStyle())
  147. .hoverOverlay(cornerRadius: 7, isEnabled: viewModel.selectedTab != tab)
  148. }
  149. }
  150. .padding(3)
  151. .frame(width: 300)
  152. .background(AppTheme.panelBackground)
  153. .clipShape(RoundedRectangle(cornerRadius: 9))
  154. .overlay(
  155. RoundedRectangle(cornerRadius: 9)
  156. .stroke(AppTheme.cardBorder, lineWidth: 1)
  157. )
  158. }
  159. // MARK: - Optimize
  160. private var optimizeContent: some View {
  161. optimizeColumns
  162. }
  163. private var optimizeColumns: some View {
  164. HStack(alignment: .top, spacing: Layout.columnSpacing) {
  165. optimizeColumn(title: "Configuration", icon: "slider.horizontal.3") {
  166. configurationPanel
  167. }
  168. .frame(width: Layout.columnWidth)
  169. .layoutPriority(1)
  170. Rectangle()
  171. .fill(AppTheme.border)
  172. .frame(width: 1)
  173. .padding(.vertical, 2)
  174. optimizeColumn(title: "Title & Suggestions", icon: "textformat") {
  175. editorPanel
  176. }
  177. .frame(minWidth: 0, maxWidth: .infinity)
  178. .layoutPriority(0)
  179. }
  180. }
  181. private func optimizeColumn<Content: View>(
  182. title: String,
  183. icon: String,
  184. @ViewBuilder content: () -> Content
  185. ) -> some View {
  186. VStack(alignment: .leading, spacing: Layout.sectionSpacing) {
  187. sectionHeader(title: title, icon: icon)
  188. content()
  189. }
  190. }
  191. private func sectionHeader(title: String, icon: String) -> some View {
  192. HStack(spacing: 6) {
  193. Image(systemName: icon)
  194. .font(.system(size: 10, weight: .semibold))
  195. .foregroundStyle(AppTheme.accentBlue)
  196. Text(title)
  197. .font(.system(size: 11, weight: .semibold))
  198. .foregroundStyle(AppTheme.textSecondary)
  199. }
  200. .textCase(.uppercase)
  201. .tracking(0.4)
  202. }
  203. private var configurationPanel: some View {
  204. VStack(spacing: Layout.sectionSpacing) {
  205. PostFormCard(title: "Target Subreddit", subtitle: "Tailor titles for the community") {
  206. PostFormField(
  207. label: "Subreddit",
  208. placeholder: "technology",
  209. text: $viewModel.draft.subreddit,
  210. prefix: "r/"
  211. )
  212. }
  213. PostFormCard(title: "AI Settings", subtitle: "Guide topic, tone, and style") {
  214. VStack(alignment: .leading, spacing: 12) {
  215. PostFormField(
  216. label: "Topic / Keywords",
  217. placeholder: "e.g. macOS productivity tips",
  218. text: $viewModel.draft.topic
  219. )
  220. VStack(alignment: .leading, spacing: 6) {
  221. Text("Tone")
  222. .font(.system(size: 10, weight: .medium))
  223. .foregroundStyle(AppTheme.textTertiary)
  224. TonePicker(selectedTone: $viewModel.draft.tone)
  225. }
  226. }
  227. }
  228. PostFormCard(title: "Title Goal", subtitle: "What kind of hook do you want?") {
  229. TitleGoalPicker(selectedGoal: $viewModel.draft.titleGoal)
  230. }
  231. PostFormCard(title: "Preview Context", subtitle: "Optional — affects preview style") {
  232. VStack(alignment: .leading, spacing: 12) {
  233. PostTypePicker(selectedType: Binding(
  234. get: { viewModel.draft.postType },
  235. set: { viewModel.selectPostType($0) }
  236. ))
  237. HStack(spacing: 8) {
  238. PostTagToggle(
  239. title: "NSFW",
  240. systemImage: "exclamationmark.triangle.fill",
  241. activeColor: Color(hex: 0xEF4444),
  242. isOn: $viewModel.draft.isNSFW
  243. )
  244. .frame(maxWidth: .infinity)
  245. PostTagToggle(
  246. title: "Spoiler",
  247. systemImage: "eye.slash.fill",
  248. activeColor: AppTheme.textSecondary,
  249. isOn: $viewModel.draft.isSpoiler
  250. )
  251. .frame(maxWidth: .infinity)
  252. PostTagToggle(
  253. title: "OC",
  254. systemImage: "star.fill",
  255. activeColor: AppTheme.accentGreen,
  256. isOn: $viewModel.draft.isOC
  257. )
  258. .frame(maxWidth: .infinity)
  259. }
  260. PostFormField(
  261. label: "Flair",
  262. placeholder: "Discussion, Question, Meme…",
  263. text: $viewModel.draft.flair
  264. )
  265. }
  266. }
  267. PostFormCard(title: "Suggestions", subtitle: "How many variants to generate") {
  268. TitleVariantCountPicker(selectedCount: $viewModel.draft.variantCount)
  269. }
  270. }
  271. }
  272. private var editorPanel: some View {
  273. VStack(spacing: Layout.sectionSpacing) {
  274. PostFormCard(title: "Original Title", subtitle: "The title you want to improve") {
  275. PostFormField(
  276. label: "Post Title",
  277. placeholder: "Enter your draft title here",
  278. text: $viewModel.draft.originalTitle
  279. )
  280. }
  281. characterCountFooter
  282. if let analysis = viewModel.analysis {
  283. TitleAnalysisCard(analysis: analysis)
  284. }
  285. suggestionsSection
  286. .id("title-suggestions")
  287. }
  288. }
  289. @ViewBuilder
  290. private var suggestionsSection: some View {
  291. PostFormCard(
  292. title: "AI Suggestions",
  293. subtitle: viewModel.variants.isEmpty
  294. ? "Hit Optimize to generate title variants"
  295. : "\(viewModel.variants.count) optimized titles ranked by score"
  296. ) {
  297. if viewModel.variants.isEmpty {
  298. TitleOptimizerEmptyState(
  299. icon: "textformat.size",
  300. title: "No suggestions yet",
  301. subtitle: "Fill in your subreddit, topic, and title,\nthen tap Optimize to get AI-powered variants."
  302. )
  303. } else {
  304. VStack(spacing: 8) {
  305. ForEach(viewModel.variants) { variant in
  306. TitleVariantRow(
  307. variant: variant,
  308. isSelected: viewModel.selectedVariantID == variant.id,
  309. onSelect: { viewModel.selectVariant(variant) },
  310. onApply: { viewModel.applyVariant(variant) }
  311. )
  312. }
  313. }
  314. }
  315. }
  316. }
  317. private var characterCountFooter: some View {
  318. HStack(spacing: 12) {
  319. Text("\(viewModel.draft.originalTitle.count) / 300")
  320. .font(.system(size: 10, weight: .medium, design: .monospaced))
  321. .foregroundStyle(
  322. viewModel.draft.originalTitle.count > 300 ? Color(hex: 0xF87171) : AppTheme.textTertiary
  323. )
  324. Spacer()
  325. Text("Reddit limit: 300 characters for title")
  326. .font(.system(size: 10))
  327. .foregroundStyle(AppTheme.textTertiary)
  328. }
  329. .padding(.horizontal, 12)
  330. .padding(.vertical, 9)
  331. .background(
  332. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  333. .fill(AppTheme.cardBackground)
  334. .overlay(
  335. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  336. .stroke(AppTheme.cardBorder, lineWidth: 1)
  337. )
  338. )
  339. }
  340. // MARK: - Compare
  341. private var compareContent: some View {
  342. VStack(alignment: .leading, spacing: Layout.columnSpacing) {
  343. compareHeader
  344. if viewModel.variants.isEmpty {
  345. TitleOptimizerEmptyState(
  346. icon: "arrow.left.arrow.right",
  347. title: "Nothing to compare yet",
  348. subtitle: "Generate title suggestions on the Optimize tab first."
  349. )
  350. .frame(maxWidth: .infinity)
  351. } else {
  352. compareBody
  353. }
  354. }
  355. }
  356. private var compareBody: some View {
  357. VStack(spacing: Layout.sectionSpacing) {
  358. TitleCompareCard(
  359. title: viewModel.draft.originalTitle,
  360. score: viewModel.analysis?.overallScore,
  361. label: "Original",
  362. isOriginal: true,
  363. isSelected: viewModel.selectedVariantID == nil
  364. )
  365. HStack {
  366. Rectangle()
  367. .fill(AppTheme.border)
  368. .frame(height: 1)
  369. Text("vs")
  370. .font(.system(size: 10, weight: .semibold))
  371. .foregroundStyle(AppTheme.textTertiary)
  372. .padding(.horizontal, 8)
  373. Rectangle()
  374. .fill(AppTheme.border)
  375. .frame(height: 1)
  376. }
  377. VStack(spacing: 8) {
  378. ForEach(viewModel.variants) { variant in
  379. TitleCompareCard(
  380. title: variant.title,
  381. score: variant.score,
  382. label: "Variant #\(variantRank(variant))",
  383. isOriginal: false,
  384. isSelected: viewModel.selectedVariantID == variant.id
  385. )
  386. .onTapGesture {
  387. viewModel.selectVariant(variant)
  388. }
  389. }
  390. }
  391. compareMetadata
  392. }
  393. .frame(maxWidth: 640)
  394. .frame(maxWidth: .infinity)
  395. }
  396. private var compareHeader: some View {
  397. HStack(alignment: .top) {
  398. sectionHeader(title: "Side-by-Side Comparison", icon: "arrow.left.arrow.right")
  399. Spacer()
  400. if let best = viewModel.bestVariant {
  401. HStack(spacing: 6) {
  402. Image(systemName: "trophy.fill")
  403. .font(.system(size: 10))
  404. .foregroundStyle(AppTheme.accentYellow)
  405. Text("Best: \(best.score)/100")
  406. .font(.system(size: 10, weight: .semibold))
  407. .foregroundStyle(AppTheme.textSecondary)
  408. }
  409. .padding(.top, 1)
  410. }
  411. }
  412. }
  413. private var compareMetadata: some View {
  414. VStack(alignment: .leading, spacing: 0) {
  415. metadataRow(label: "Subreddit", value: viewModel.formattedSubreddit)
  416. metadataDivider
  417. metadataRow(label: "Goal", value: viewModel.draft.titleGoal.title)
  418. metadataDivider
  419. metadataRow(label: "Tone", value: viewModel.draft.tone.title)
  420. metadataDivider
  421. metadataRow(label: "Engine", value: viewModel.usesLiveAI ? "OpenAI" : "Local templates")
  422. metadataDivider
  423. metadataRow(label: "Active", value: viewModel.activeTitle)
  424. }
  425. .padding(14)
  426. .frame(maxWidth: .infinity, alignment: .leading)
  427. .background(
  428. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  429. .fill(AppTheme.cardBackground)
  430. .overlay(
  431. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  432. .stroke(AppTheme.cardBorder, lineWidth: 1)
  433. )
  434. )
  435. }
  436. private func variantRank(_ variant: TitleVariant) -> Int {
  437. (viewModel.variants.firstIndex(where: { $0.id == variant.id }) ?? 0) + 1
  438. }
  439. // MARK: - Preview
  440. private var previewContent: some View {
  441. VStack(alignment: .leading, spacing: Layout.columnSpacing) {
  442. sectionHeader(title: "Live Preview", icon: "eye")
  443. HStack {
  444. Spacer(minLength: 0)
  445. VStack(spacing: Layout.sectionSpacing) {
  446. RedditPostPreviewCard(
  447. draft: viewModel.previewDraft,
  448. formattedSubreddit: viewModel.formattedSubreddit
  449. )
  450. PostFormCard(title: "Feed Preview", subtitle: "How your title looks in a crowded feed") {
  451. VStack(spacing: 6) {
  452. TitleFeedPreviewRow(
  453. title: "Other trending post in this subreddit right now",
  454. subreddit: viewModel.formattedSubreddit
  455. )
  456. TitleFeedPreviewRow(
  457. title: viewModel.activeTitle,
  458. subreddit: viewModel.formattedSubreddit,
  459. isHighlighted: true
  460. )
  461. TitleFeedPreviewRow(
  462. title: "Another popular discussion happening nearby",
  463. subreddit: viewModel.formattedSubreddit
  464. )
  465. }
  466. }
  467. previewMetadata
  468. }
  469. .frame(maxWidth: 560)
  470. Spacer(minLength: 0)
  471. }
  472. }
  473. }
  474. private var previewMetadata: some View {
  475. VStack(alignment: .leading, spacing: 0) {
  476. metadataRow(label: "Active Title", value: viewModel.activeTitle)
  477. metadataDivider
  478. metadataRow(label: "Subreddit", value: viewModel.formattedSubreddit)
  479. metadataDivider
  480. metadataRow(label: "Goal", value: viewModel.draft.titleGoal.title)
  481. metadataDivider
  482. metadataRow(label: "Tone", value: viewModel.draft.tone.title)
  483. metadataDivider
  484. metadataRow(label: "Type", value: viewModel.draft.postType.title)
  485. metadataDivider
  486. metadataRow(label: "Engine", value: viewModel.usesLiveAI ? "OpenAI" : "Local templates")
  487. if let score = viewModel.analysis?.overallScore {
  488. metadataDivider
  489. metadataRow(label: "Score", value: "\(score)/100")
  490. }
  491. if viewModel.draft.isNSFW || viewModel.draft.isSpoiler || viewModel.draft.isOC {
  492. metadataDivider
  493. metadataRow(
  494. label: "Tags",
  495. value: [
  496. viewModel.draft.isNSFW ? "NSFW" : nil,
  497. viewModel.draft.isSpoiler ? "Spoiler" : nil,
  498. viewModel.draft.isOC ? "OC" : nil,
  499. ]
  500. .compactMap { $0 }
  501. .joined(separator: ", ")
  502. )
  503. }
  504. }
  505. .padding(14)
  506. .frame(maxWidth: .infinity, alignment: .leading)
  507. .background(
  508. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  509. .fill(AppTheme.cardBackground)
  510. .overlay(
  511. RoundedRectangle(cornerRadius: AppTheme.cornerRadiusSmall)
  512. .stroke(AppTheme.cardBorder, lineWidth: 1)
  513. )
  514. )
  515. }
  516. private var metadataDivider: some View {
  517. Rectangle()
  518. .fill(AppTheme.border)
  519. .frame(height: 1)
  520. .padding(.vertical, 6)
  521. }
  522. private func metadataRow(label: String, value: String) -> some View {
  523. HStack(alignment: .top, spacing: 12) {
  524. Text(label)
  525. .font(.system(size: 10, weight: .medium))
  526. .foregroundStyle(AppTheme.textTertiary)
  527. .frame(width: 72, alignment: .leading)
  528. Text(value)
  529. .font(.system(size: 10))
  530. .foregroundStyle(AppTheme.textSecondary)
  531. .fixedSize(horizontal: false, vertical: true)
  532. }
  533. }
  534. }
  535. private struct TitleSecondaryButtonStyle: ButtonStyle {
  536. func makeBody(configuration: Configuration) -> some View {
  537. AppSecondaryButtonStyle().makeBody(configuration: configuration)
  538. }
  539. }
  540. #Preview {
  541. TitleOptimizerView(viewModel: TitleOptimizerViewModel())
  542. .frame(width: 880, height: 720)
  543. }