PaywallView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. import AppKit
  2. import StoreKit
  3. import SwiftUI
  4. struct PaywallView: View {
  5. @EnvironmentObject private var subscriptions: SubscriptionManager
  6. @ObservedObject private var paywallConfigService = PaywallConfigService.shared
  7. @Bindable var viewModel: PaywallViewModel
  8. var onDismiss: () -> Void
  9. private var config: PaywallConfig { paywallConfigService.config }
  10. private var isPurchasingSelectedPlan: Bool {
  11. subscriptions.purchasingPlan == viewModel.selectedPlan
  12. }
  13. private var buttonsBusy: Bool {
  14. subscriptions.purchasingPlan != nil || subscriptions.isRestoringPurchases
  15. }
  16. private var isPremium: Bool {
  17. subscriptions.hasPremiumAccess
  18. }
  19. private var hasProductLoadFailure: Bool {
  20. subscriptions.productLoadError != nil && !subscriptions.hasAllProductsLoaded
  21. }
  22. private var isProductReady: Bool {
  23. subscriptions.product(for: viewModel.selectedPlan) != nil
  24. }
  25. private var availablePlans: [PaywallPlan] {
  26. subscriptions.availablePaywallPlans
  27. }
  28. var body: some View {
  29. GeometryReader { geometry in
  30. let metrics = PaywallLayoutMetrics(size: geometry.size)
  31. ZStack {
  32. AppTheme.background
  33. .ignoresSafeArea()
  34. VStack(spacing: metrics.sectionSpacing) {
  35. header(metrics: metrics)
  36. featuresSection(metrics: metrics)
  37. if hasProductLoadFailure {
  38. productsErrorSection(metrics: metrics)
  39. } else {
  40. pricingCards(metrics: metrics)
  41. }
  42. ctaSection(metrics: metrics)
  43. Spacer(minLength: 0)
  44. footerLinks(metrics: metrics)
  45. }
  46. .padding(.horizontal, metrics.horizontalInset)
  47. .padding(.top, metrics.topInset)
  48. .padding(.bottom, metrics.bottomInset)
  49. .frame(width: geometry.size.width, height: geometry.size.height, alignment: .top)
  50. if subscriptions.isLoadingProducts && !subscriptions.hasAllProductsLoaded && !hasProductLoadFailure {
  51. AppTheme.scrim
  52. .ignoresSafeArea()
  53. .allowsHitTesting(false)
  54. ProgressView()
  55. .controlSize(.large)
  56. }
  57. if isPremium {
  58. closeButton(metrics: metrics)
  59. }
  60. }
  61. }
  62. .frame(maxWidth: .infinity, maxHeight: .infinity)
  63. .ignoresSafeArea()
  64. .task {
  65. await subscriptions.ensureEntitlementsResolved()
  66. if !subscriptions.hasAllProductsLoaded, !subscriptions.isLoadingProducts {
  67. await subscriptions.loadProducts(presentLoadingUI: true)
  68. }
  69. await subscriptions.refreshTrialEligibility()
  70. await paywallConfigService.refreshFromRemote()
  71. viewModel.syncSelectedPlan(with: availablePlans)
  72. }
  73. .onChange(of: subscriptions.hasEverPurchasedPremium) { _, _ in
  74. Task { await subscriptions.refreshTrialEligibility() }
  75. viewModel.syncSelectedPlan(with: availablePlans)
  76. if let eligiblePlan = config.trialEligiblePlan,
  77. subscriptions.trialDisplay(for: eligiblePlan) != nil {
  78. viewModel.selectPlan(eligiblePlan)
  79. }
  80. }
  81. .onChange(of: subscriptions.hasPremiumAccess) { _, _ in
  82. Task { await subscriptions.refreshTrialEligibility() }
  83. }
  84. .onChange(of: subscriptions.hasAllProductsLoaded) { _, loaded in
  85. if loaded {
  86. Task { await subscriptions.refreshTrialEligibility() }
  87. }
  88. }
  89. .onChange(of: subscriptions.trialDisplayByPlan) { _, _ in
  90. if let eligiblePlan = config.trialEligiblePlan,
  91. subscriptions.trialDisplay(for: eligiblePlan) != nil {
  92. viewModel.selectPlan(eligiblePlan)
  93. }
  94. }
  95. .onChange(of: subscriptions.availablePaywallPlans) { _, plans in
  96. viewModel.syncSelectedPlan(with: plans)
  97. if let eligiblePlan = config.trialEligiblePlan,
  98. subscriptions.trialDisplay(for: eligiblePlan) != nil {
  99. viewModel.selectPlan(eligiblePlan)
  100. }
  101. }
  102. .onReceive(NotificationCenter.default.publisher(for: .paywallConfigDidUpdate)) { _ in
  103. Task { await subscriptions.loadProducts(presentLoadingUI: false) }
  104. }
  105. .alert(
  106. config.messages.purchaseFailedTitle,
  107. isPresented: Binding(
  108. get: { subscriptions.purchaseError != nil },
  109. set: { presented in
  110. if !presented { subscriptions.purchaseError = nil }
  111. }
  112. )
  113. ) {
  114. Button(config.messages.alertOK, role: .cancel) {}
  115. } message: {
  116. Text(subscriptions.purchaseError.map { config.message(for: $0) } ?? "")
  117. }
  118. }
  119. private func closeButton(metrics: PaywallLayoutMetrics) -> some View {
  120. VStack {
  121. HStack {
  122. Spacer()
  123. Button(action: onDismiss) {
  124. Image(systemName: "xmark")
  125. .font(.system(size: metrics.closeButtonSize, weight: .medium))
  126. .foregroundStyle(AppTheme.textSecondary)
  127. .frame(width: metrics.closeButtonHitArea, height: metrics.closeButtonHitArea)
  128. .background(
  129. Circle()
  130. .fill(AppTheme.cardBackground)
  131. .overlay(
  132. Circle()
  133. .stroke(AppTheme.cardBorder, lineWidth: 1)
  134. )
  135. )
  136. }
  137. .buttonStyle(AppPlainButtonStyle())
  138. .help(config.closeButtonHelp)
  139. }
  140. Spacer()
  141. }
  142. .padding(.trailing, metrics.horizontalInset * 0.55)
  143. .padding(.top, metrics.topInset * 0.28)
  144. }
  145. private func header(metrics: PaywallLayoutMetrics) -> some View {
  146. VStack(spacing: metrics.headerSpacing) {
  147. Text(config.rightTitle)
  148. .font(.system(size: metrics.titleFontSize, weight: .bold))
  149. .foregroundStyle(AppTheme.textPrimary)
  150. Text(config.rightSubtitle)
  151. .font(.system(size: metrics.subtitleFontSize))
  152. .foregroundStyle(AppTheme.textSecondary)
  153. .multilineTextAlignment(.center)
  154. .frame(maxWidth: metrics.subtitleMaxWidth)
  155. }
  156. .frame(maxWidth: .infinity)
  157. }
  158. private func featuresSection(metrics: PaywallLayoutMetrics) -> some View {
  159. VStack(alignment: .leading, spacing: metrics.featureSectionSpacing) {
  160. Text(config.leftPanelTitle)
  161. .font(.system(size: metrics.sectionTitleFontSize, weight: .semibold))
  162. .foregroundStyle(AppTheme.textPrimary)
  163. LazyVGrid(columns: metrics.featureColumns, alignment: .leading, spacing: metrics.featureRowSpacing) {
  164. ForEach(Array(config.features.enumerated()), id: \.offset) { _, feature in
  165. PaywallFeatureRow(title: feature, metrics: metrics)
  166. }
  167. }
  168. }
  169. .frame(maxWidth: .infinity, alignment: .leading)
  170. }
  171. private func productsErrorSection(metrics: PaywallLayoutMetrics) -> some View {
  172. VStack(spacing: metrics.ctaSpacing) {
  173. Text(subscriptions.productLoadError ?? config.messages.plansLoadFailed)
  174. .font(.system(size: metrics.footerNoteFontSize))
  175. .foregroundStyle(AppTheme.textSecondary)
  176. .multilineTextAlignment(.center)
  177. Button(subscriptions.isLoadingProducts ? config.messages.retrying : config.messages.retry) {
  178. Task { await subscriptions.loadProducts(presentLoadingUI: true) }
  179. }
  180. .buttonStyle(AppTextLinkButtonStyle())
  181. .font(.system(size: metrics.footerLinkFontSize))
  182. .foregroundStyle(AppTheme.textSecondary)
  183. .disabled(subscriptions.isLoadingProducts)
  184. }
  185. .frame(maxWidth: .infinity, minHeight: metrics.cardMinHeight)
  186. }
  187. private func pricingCards(metrics: PaywallLayoutMetrics) -> some View {
  188. HStack(alignment: .top, spacing: metrics.cardSpacing) {
  189. ForEach(availablePlans) { plan in
  190. PaywallPricingCard(
  191. plan: plan,
  192. config: config,
  193. product: subscriptions.product(for: plan),
  194. trial: subscriptions.trialDisplay(for: plan),
  195. isSelected: viewModel.selectedPlan == plan,
  196. metrics: metrics
  197. ) {
  198. viewModel.selectPlan(plan)
  199. subscriptions.purchaseError = nil
  200. }
  201. }
  202. }
  203. .frame(maxWidth: .infinity)
  204. }
  205. private func ctaSection(metrics: PaywallLayoutMetrics) -> some View {
  206. let selectedProduct = subscriptions.product(for: viewModel.selectedPlan)
  207. let selectedTrial = subscriptions.trialDisplay(for: viewModel.selectedPlan)
  208. let ctaDisabled = buttonsBusy || subscriptions.isLoadingProducts || !isProductReady || hasProductLoadFailure
  209. return VStack(spacing: metrics.ctaSpacing) {
  210. Text(
  211. viewModel.selectedPlan.localizedRenewalDisclosure(
  212. from: selectedProduct,
  213. config: config,
  214. trial: selectedTrial
  215. )
  216. )
  217. .font(.system(size: metrics.footerNoteFontSize))
  218. .foregroundStyle(AppTheme.textTertiary)
  219. .multilineTextAlignment(.center)
  220. Button {
  221. Task {
  222. let purchased = await subscriptions.purchase(viewModel.selectedPlan)
  223. if purchased {
  224. onDismiss()
  225. }
  226. }
  227. } label: {
  228. HStack(spacing: 8) {
  229. if isPurchasingSelectedPlan {
  230. ProgressView()
  231. .controlSize(.small)
  232. .tint(Color(hex: 0x0B0E14))
  233. }
  234. Text(
  235. viewModel.selectedPlan.localizedCTATitle(
  236. from: selectedProduct,
  237. config: config,
  238. trial: selectedTrial
  239. )
  240. )
  241. .font(.system(size: metrics.ctaFontSize, weight: .bold))
  242. .foregroundStyle(Color(hex: 0x0B0E14))
  243. }
  244. .frame(maxWidth: .infinity)
  245. .padding(.vertical, metrics.ctaVerticalPadding)
  246. .background(
  247. LinearGradient(
  248. colors: [AppTheme.accentPurpleLight, AppTheme.accentTeal],
  249. startPoint: .leading,
  250. endPoint: .trailing
  251. )
  252. )
  253. .clipShape(RoundedRectangle(cornerRadius: metrics.cornerRadius))
  254. }
  255. .buttonStyle(AppPrimaryButtonStyle())
  256. .disabled(ctaDisabled)
  257. .opacity(ctaDisabled ? 0.7 : 1)
  258. HStack(spacing: 6) {
  259. Image(systemName: "lock.fill")
  260. .font(.system(size: metrics.footerNoteFontSize))
  261. Text(config.securePaymentNote)
  262. .font(.system(size: metrics.footerNoteFontSize))
  263. }
  264. .foregroundStyle(AppTheme.textTertiary)
  265. }
  266. }
  267. private func footerLinks(metrics: PaywallLayoutMetrics) -> some View {
  268. HStack(spacing: 0) {
  269. if !isPremium {
  270. footerLink(config.footer.continueFree, metrics: metrics) {
  271. onDismiss()
  272. }
  273. Spacer(minLength: metrics.footerLinkSpacing)
  274. } else if subscriptions.hasActiveSubscription {
  275. footerLink(config.footer.manageSubscription, metrics: metrics) {
  276. subscriptions.openSubscriptionManagement()
  277. }
  278. Spacer(minLength: metrics.footerLinkSpacing)
  279. }
  280. footerLink(
  281. subscriptions.isRestoringPurchases ? config.messages.retrying : config.footer.restorePurchase,
  282. metrics: metrics
  283. ) {
  284. Task {
  285. await subscriptions.restorePurchases()
  286. if subscriptions.hasPremiumAccess {
  287. onDismiss()
  288. }
  289. }
  290. }
  291. .disabled(subscriptions.isRestoringPurchases)
  292. Spacer(minLength: metrics.footerLinkSpacing)
  293. footerLink(config.footer.privacyPolicy, metrics: metrics) {
  294. openExternalLink(config.urls.privacy)
  295. }
  296. Spacer(minLength: metrics.footerLinkSpacing)
  297. footerLink(config.footer.support, metrics: metrics) {
  298. openExternalLink(config.urls.support)
  299. }
  300. Spacer(minLength: metrics.footerLinkSpacing)
  301. footerLink(config.footer.termsOfService, metrics: metrics) {
  302. openExternalLink(config.urls.terms)
  303. }
  304. }
  305. .padding(.horizontal, metrics.footerLinksHorizontalInset)
  306. .frame(maxWidth: .infinity)
  307. }
  308. private func openExternalLink(_ urlString: String) {
  309. guard let url = URL(string: urlString) else { return }
  310. NSWorkspace.shared.open(url)
  311. }
  312. private func footerLink(_ title: String, metrics: PaywallLayoutMetrics, action: @escaping () -> Void) -> some View {
  313. Button(title, action: action)
  314. .buttonStyle(AppTextLinkButtonStyle())
  315. .font(.system(size: metrics.footerLinkFontSize))
  316. .foregroundStyle(AppTheme.textSecondary)
  317. .lineLimit(1)
  318. .minimumScaleFactor(0.8)
  319. }
  320. }
  321. // MARK: - Layout Metrics
  322. private struct PaywallLayoutMetrics {
  323. let size: CGSize
  324. var horizontalInset: CGFloat { size.width * 0.06 }
  325. var topInset: CGFloat { size.height * 0.11 }
  326. var bottomInset: CGFloat { size.height * 0.05 }
  327. var sectionSpacing: CGFloat { size.height * 0.04 }
  328. var headerSpacing: CGFloat { size.height * 0.012 }
  329. var featureSectionSpacing: CGFloat { size.height * 0.018 }
  330. var featureRowSpacing: CGFloat { size.height * 0.016 }
  331. var cardSpacing: CGFloat { size.width * 0.018 }
  332. var ctaSpacing: CGFloat { size.height * 0.014 }
  333. var footerLinkSpacing: CGFloat { size.width * 0.018 }
  334. var footerLinksHorizontalInset: CGFloat { size.width * 0.035 }
  335. var titleFontSize: CGFloat { clamp(size.height * 0.043, min: 22, max: 36) }
  336. var subtitleFontSize: CGFloat { clamp(size.height * 0.02, min: 12, max: 16) }
  337. var sectionTitleFontSize: CGFloat { clamp(size.height * 0.018, min: 11, max: 14) }
  338. var featureFontSize: CGFloat { clamp(size.height * 0.017, min: 10, max: 13) }
  339. var ctaFontSize: CGFloat { clamp(size.height * 0.022, min: 13, max: 16) }
  340. var footerNoteFontSize: CGFloat { clamp(size.height * 0.015, min: 9, max: 12) }
  341. var footerLinkFontSize: CGFloat { clamp(size.height * 0.015, min: 9, max: 12) }
  342. var subtitleMaxWidth: CGFloat { size.width * 0.55 }
  343. var cardMinHeight: CGFloat { size.height * 0.32 }
  344. var cardPadding: CGFloat { size.width * 0.014 }
  345. var cornerRadius: CGFloat { clamp(size.height * 0.014, min: 8, max: 12) }
  346. var ctaVerticalPadding: CGFloat { size.height * 0.022 }
  347. var closeButtonSize: CGFloat { clamp(size.height * 0.016, min: 10, max: 14) }
  348. var closeButtonHitArea: CGFloat { clamp(size.height * 0.038, min: 28, max: 36) }
  349. var featureColumns: [GridItem] {
  350. [
  351. GridItem(.flexible(), spacing: featureRowSpacing),
  352. GridItem(.flexible(), spacing: featureRowSpacing),
  353. GridItem(.flexible(), spacing: featureRowSpacing),
  354. ]
  355. }
  356. private func clamp(_ value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
  357. Swift.min(Swift.max(value, min), max)
  358. }
  359. }
  360. // MARK: - Components
  361. private struct PaywallFeatureRow: View {
  362. let title: String
  363. let metrics: PaywallLayoutMetrics
  364. var body: some View {
  365. HStack(spacing: 8) {
  366. Image(systemName: "checkmark")
  367. .font(.system(size: metrics.featureFontSize * 0.75, weight: .bold))
  368. .foregroundStyle(AppTheme.accentGreen)
  369. .frame(width: metrics.featureFontSize + 4)
  370. Text(title)
  371. .font(.system(size: metrics.featureFontSize))
  372. .foregroundStyle(AppTheme.textSecondary)
  373. .lineLimit(1)
  374. .minimumScaleFactor(0.85)
  375. }
  376. }
  377. }
  378. private struct PaywallPricingCard: View {
  379. let plan: PaywallPlan
  380. let config: PaywallConfig
  381. let product: Product?
  382. let trial: PaywallTrialDisplay?
  383. let isSelected: Bool
  384. let metrics: PaywallLayoutMetrics
  385. let onSelect: () -> Void
  386. private var planCopy: PaywallConfig.PlanCopy {
  387. plan.planCopy(from: config, product: product)
  388. }
  389. var body: some View {
  390. Button(action: onSelect) {
  391. VStack(alignment: .leading, spacing: 0) {
  392. Color.clear
  393. .frame(height: metrics.cardPadding * 1.0)
  394. .padding(.bottom, metrics.cardPadding * 0.15)
  395. Text(planCopy.title)
  396. .font(.system(size: metrics.ctaFontSize, weight: .semibold))
  397. .foregroundStyle(AppTheme.textPrimary)
  398. if product != nil {
  399. Text(plan.localizedSubtitle(from: product, config: config, trial: trial))
  400. .font(.system(size: metrics.featureFontSize * 0.85))
  401. .foregroundStyle(AppTheme.textTertiary)
  402. .fixedSize(horizontal: false, vertical: true)
  403. .padding(.top, 2)
  404. }
  405. HStack(alignment: .firstTextBaseline, spacing: 2) {
  406. Text(plan.localizedPrice(from: product, config: config))
  407. .font(.system(size: metrics.titleFontSize * 0.85, weight: .bold))
  408. .foregroundStyle(AppTheme.textPrimary)
  409. if product != nil, let priceSuffix = planCopy.priceSuffix {
  410. Text(priceSuffix)
  411. .font(.system(size: metrics.featureFontSize))
  412. .foregroundStyle(AppTheme.textSecondary)
  413. }
  414. }
  415. .padding(.top, metrics.cardPadding)
  416. .padding(.bottom, metrics.cardPadding * 0.9)
  417. VStack(alignment: .leading, spacing: metrics.featureRowSpacing * 0.7) {
  418. ForEach(planCopy.features, id: \.self) { feature in
  419. HStack(alignment: .top, spacing: 8) {
  420. Image(systemName: "checkmark")
  421. .font(.system(size: metrics.featureFontSize * 0.75, weight: .bold))
  422. .foregroundStyle(AppTheme.accentGreen)
  423. .padding(.top, 2)
  424. Text(feature)
  425. .font(.system(size: metrics.featureFontSize * 0.92))
  426. .foregroundStyle(AppTheme.textSecondary)
  427. .fixedSize(horizontal: false, vertical: true)
  428. .multilineTextAlignment(.leading)
  429. }
  430. }
  431. }
  432. Spacer(minLength: 0)
  433. }
  434. .padding(metrics.cardPadding)
  435. .frame(maxWidth: .infinity, minHeight: metrics.cardMinHeight, alignment: .topLeading)
  436. .background(
  437. RoundedRectangle(cornerRadius: metrics.cornerRadius)
  438. .fill(AppTheme.cardBackground)
  439. )
  440. .overlay(
  441. RoundedRectangle(cornerRadius: metrics.cornerRadius)
  442. .stroke(
  443. isSelected ? AppTheme.accentTeal : AppTheme.cardBorder,
  444. lineWidth: isSelected ? 2 : 1
  445. )
  446. )
  447. .overlay(alignment: .topTrailing) {
  448. if let trial {
  449. cardBadge(trial.badgeText)
  450. } else if let badge = planCopy.badge, plan.isLifetime {
  451. cardBadge(badge)
  452. }
  453. }
  454. }
  455. .buttonStyle(AppPlainButtonStyle())
  456. .hoverCard(cornerRadius: metrics.cornerRadius, isSelected: isSelected)
  457. }
  458. private func cardBadge(_ text: String) -> some View {
  459. Text(text)
  460. .font(.system(size: metrics.featureFontSize * 0.75, weight: .bold))
  461. .foregroundStyle(Color(hex: 0x0B0E14))
  462. .padding(.horizontal, 10)
  463. .padding(.vertical, 4)
  464. .background(AppTheme.accentTeal)
  465. .clipShape(Capsule())
  466. .padding(.top, metrics.cardPadding * 0.65)
  467. .padding(.trailing, metrics.cardPadding * 0.65)
  468. }
  469. }
  470. #Preview {
  471. let subscriptions = SubscriptionManager()
  472. return PaywallView(viewModel: PaywallViewModel(), onDismiss: {})
  473. .environmentObject(subscriptions)
  474. .frame(width: AppWindow.width, height: AppWindow.height)
  475. .onAppear {
  476. subscriptions.start()
  477. PaywallConfigService.shared.start()
  478. }
  479. }