Sin descripción

PremiumPlansWindowController.swift 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. import Cocoa
  2. import StoreKit
  3. final class PremiumPlansWindowController: NSWindowController {
  4. init() {
  5. let viewController = PremiumPlansViewController()
  6. let window = NSWindow(contentViewController: viewController)
  7. window.title = "Premium Plans"
  8. window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
  9. window.styleMask.insert(.fullSizeContentView)
  10. window.titlebarAppearsTransparent = true
  11. window.titleVisibility = .hidden
  12. window.isOpaque = false
  13. window.backgroundColor = .clear
  14. window.setContentSize(NSSize(width: 1160, height: 760))
  15. window.minSize = NSSize(width: 980, height: 680)
  16. window.center()
  17. super.init(window: window)
  18. if let frameView = window.contentView?.superview {
  19. frameView.wantsLayer = true
  20. frameView.layer?.cornerRadius = 18
  21. frameView.layer?.masksToBounds = true
  22. }
  23. }
  24. @available(*, unavailable)
  25. required init?(coder: NSCoder) {
  26. nil
  27. }
  28. }
  29. private final class PremiumPlansViewController: NSViewController {
  30. private final class HoverPricingCardView: NSView {
  31. private let baseBorderColor: NSColor
  32. private let hoverBorderColor: NSColor
  33. private var trackingAreaRef: NSTrackingArea?
  34. init(baseBorderColor: NSColor, hoverBorderColor: NSColor) {
  35. self.baseBorderColor = baseBorderColor
  36. self.hoverBorderColor = hoverBorderColor
  37. super.init(frame: .zero)
  38. wantsLayer = true
  39. layer?.cornerRadius = 16
  40. applyHoverStyle(isHovered: false, animated: false)
  41. }
  42. @available(*, unavailable)
  43. required init?(coder: NSCoder) {
  44. nil
  45. }
  46. override func updateTrackingAreas() {
  47. super.updateTrackingAreas()
  48. if let trackingAreaRef {
  49. removeTrackingArea(trackingAreaRef)
  50. }
  51. let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
  52. let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
  53. addTrackingArea(area)
  54. trackingAreaRef = area
  55. }
  56. override func mouseEntered(with event: NSEvent) {
  57. super.mouseEntered(with: event)
  58. applyHoverStyle(isHovered: true, animated: true)
  59. }
  60. override func mouseExited(with event: NSEvent) {
  61. super.mouseExited(with: event)
  62. applyHoverStyle(isHovered: false, animated: true)
  63. }
  64. private func applyHoverStyle(isHovered: Bool, animated: Bool) {
  65. guard let layer else { return }
  66. let updates = {
  67. layer.borderWidth = isHovered ? 2 : 1
  68. layer.borderColor = (isHovered ? self.hoverBorderColor : self.baseBorderColor).cgColor
  69. layer.shadowColor = self.hoverBorderColor.withAlphaComponent(0.35).cgColor
  70. layer.shadowOpacity = isHovered ? 0.22 : 0
  71. layer.shadowRadius = isHovered ? 14 : 0
  72. layer.shadowOffset = .init(width: 0, height: -2)
  73. }
  74. if animated {
  75. NSAnimationContext.runAnimationGroup { context in
  76. context.duration = 0.16
  77. updates()
  78. }
  79. } else {
  80. updates()
  81. }
  82. }
  83. }
  84. private struct Plan {
  85. let id: String
  86. let title: String
  87. let subtitle: String
  88. let price: String
  89. let period: String
  90. let billedPill: String
  91. let billedLine: String
  92. let crossedPrice: String?
  93. let savingsText: String?
  94. let features: [String]
  95. let iconName: String
  96. let iconTint: NSColor
  97. let highlight: Bool
  98. }
  99. private enum Theme {
  100. static let pageStart = NSColor(srgbRed: 249 / 255, green: 252 / 255, blue: 255 / 255, alpha: 1)
  101. static let pageEnd = NSColor(srgbRed: 238 / 255, green: 244 / 255, blue: 255 / 255, alpha: 1)
  102. static let cardBackground = NSColor.white
  103. static let primaryText = NSColor(srgbRed: 27 / 255, green: 38 / 255, blue: 79 / 255, alpha: 1)
  104. static let secondaryText = NSColor(srgbRed: 108 / 255, green: 120 / 255, blue: 157 / 255, alpha: 1)
  105. static let cardBorder = NSColor(srgbRed: 198 / 255, green: 216 / 255, blue: 255 / 255, alpha: 1)
  106. static let accent = NSColor(srgbRed: 55 / 255, green: 128 / 255, blue: 255 / 255, alpha: 1)
  107. static let accentHover = NSColor(srgbRed: 38 / 255, green: 108 / 255, blue: 232 / 255, alpha: 1)
  108. static let mutedButtonFill = NSColor(srgbRed: 238 / 255, green: 243 / 255, blue: 252 / 255, alpha: 1)
  109. static let bottomStrip = NSColor(srgbRed: 244 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1)
  110. static let divider = NSColor(srgbRed: 218 / 255, green: 228 / 255, blue: 247 / 255, alpha: 1)
  111. static let successText = NSColor(srgbRed: 21 / 255, green: 154 / 255, blue: 220 / 255, alpha: 1)
  112. static let iconTint = NSColor(srgbRed: 47 / 255, green: 136 / 255, blue: 255 / 255, alpha: 1)
  113. }
  114. private enum FeatureListMetrics {
  115. static let spacing = CGFloat(10)
  116. static let edgeInsets = NSEdgeInsets(top: 21, left: 37, bottom: 21, right: 0)
  117. }
  118. private let subscriptionStore = SubscriptionStore.shared
  119. private var planPriceFields: [String: (price: NSTextField, period: NSTextField)] = [:]
  120. private var planPurchaseButtons: [String: NSButton] = [:]
  121. private var subscriptionPrimaryFooterButton: NSButton?
  122. private var premiumCloseButton: NSButton?
  123. private var subscriptionStatusObservation: NSObjectProtocol?
  124. private let plans: [Plan] = [
  125. Plan(
  126. id: "weekly",
  127. title: "Weekly",
  128. subtitle: "Flexible and commitment-free",
  129. price: "$9.99",
  130. period: "/ week",
  131. billedPill: "",
  132. billedLine: "",
  133. crossedPrice: nil,
  134. savingsText: nil,
  135. features: [
  136. "All premium features",
  137. "Perfect for short-term goals",
  138. "Cancel anytime"
  139. ],
  140. iconName: "paperplane.fill",
  141. iconTint: Theme.iconTint,
  142. highlight: false
  143. ),
  144. Plan(
  145. id: "monthly",
  146. title: "Monthly",
  147. subtitle: "Balanced for regular productivity",
  148. price: "$19.99",
  149. period: "/ month",
  150. billedPill: "",
  151. billedLine: "",
  152. crossedPrice: nil,
  153. savingsText: nil,
  154. features: [
  155. "All premium features",
  156. "Best value for regular users",
  157. "Priority support"
  158. ],
  159. iconName: "bolt.fill",
  160. iconTint: Theme.accent,
  161. highlight: true
  162. ),
  163. Plan(
  164. id: "yearly",
  165. title: "Yearly",
  166. subtitle: "Best value for long-term users",
  167. price: "$39.99",
  168. period: "/ year",
  169. billedPill: "3 days free trial",
  170. billedLine: "",
  171. crossedPrice: nil,
  172. savingsText: nil,
  173. features: [
  174. "All premium features",
  175. "Lowest effective monthly cost",
  176. "Ideal for long-term use"
  177. ],
  178. iconName: "crown.fill",
  179. iconTint: Theme.successText,
  180. highlight: false
  181. )
  182. ]
  183. private let pageGradient = CAGradientLayer()
  184. deinit {
  185. if let subscriptionStatusObservation {
  186. NotificationCenter.default.removeObserver(subscriptionStatusObservation)
  187. }
  188. }
  189. override func viewDidLoad() {
  190. super.viewDidLoad()
  191. subscriptionStatusObservation = NotificationCenter.default.addObserver(
  192. forName: .subscriptionStatusDidChange,
  193. object: nil,
  194. queue: .main
  195. ) { [weak self] _ in
  196. Task { @MainActor in
  197. await self?.subscriptionStore.loadProducts()
  198. self?.applyStorePricing()
  199. self?.updateSubscriptionPrimaryFooter()
  200. self?.updatePremiumCloseButtonVisibility()
  201. }
  202. }
  203. Task { await loadStoreProducts() }
  204. }
  205. override func viewDidLayout() {
  206. super.viewDidLayout()
  207. pageGradient.frame = view.bounds
  208. }
  209. override func loadView() {
  210. view = NSView()
  211. view.wantsLayer = true
  212. view.layer?.cornerRadius = 18
  213. view.layer?.masksToBounds = true
  214. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  215. pageGradient.startPoint = CGPoint(x: 0, y: 1)
  216. pageGradient.endPoint = CGPoint(x: 1, y: 0)
  217. view.layer?.addSublayer(pageGradient)
  218. setupLayout()
  219. }
  220. private func setupLayout() {
  221. let closeButton = NSButton(title: "", target: self, action: #selector(didTapClose))
  222. closeButton.translatesAutoresizingMaskIntoConstraints = false
  223. closeButton.isBordered = false
  224. closeButton.wantsLayer = true
  225. closeButton.layer?.cornerRadius = 15
  226. closeButton.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.92).cgColor
  227. closeButton.layer?.borderWidth = 1
  228. closeButton.layer?.borderColor = Theme.divider.cgColor
  229. closeButton.contentTintColor = Theme.secondaryText
  230. closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close")
  231. closeButton.imageScaling = .scaleProportionallyDown
  232. closeButton.bezelStyle = .regularSquare
  233. let crownIcon = NSImageView()
  234. crownIcon.translatesAutoresizingMaskIntoConstraints = false
  235. crownIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  236. crownIcon.image = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: nil)
  237. crownIcon.contentTintColor = NSColor(srgbRed: 254 / 255, green: 214 / 255, blue: 92 / 255, alpha: 1)
  238. let title = NSTextField(labelWithString: "Upgrade to Pro")
  239. title.font = .systemFont(ofSize: 40, weight: .semibold)
  240. title.textColor = Theme.primaryText
  241. title.alignment = .center
  242. let subtitle = NSTextField(labelWithString: "Unlock unlimited access to premium tools and boost your productivity.")
  243. subtitle.font = .systemFont(ofSize: 14, weight: .regular)
  244. subtitle.textColor = Theme.secondaryText
  245. subtitle.alignment = .center
  246. let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
  247. cardsRow.orientation = .horizontal
  248. cardsRow.spacing = 14
  249. cardsRow.alignment = .top
  250. cardsRow.distribution = .fillEqually
  251. cardsRow.translatesAutoresizingMaskIntoConstraints = false
  252. for card in cardsRow.arrangedSubviews {
  253. card.heightAnchor.constraint(equalTo: cardsRow.heightAnchor).isActive = true
  254. }
  255. let trustRow = makeTrustRow()
  256. let footerRow = makeFooterRow()
  257. let root = NSStackView(views: [crownIcon, title, subtitle, cardsRow, trustRow, footerRow])
  258. root.orientation = .vertical
  259. root.spacing = 18
  260. root.alignment = .centerX
  261. root.translatesAutoresizingMaskIntoConstraints = false
  262. view.addSubview(root)
  263. view.addSubview(closeButton)
  264. NSLayoutConstraint.activate([
  265. root.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  266. root.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  267. root.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
  268. root.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
  269. closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  270. closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
  271. closeButton.widthAnchor.constraint(equalToConstant: 30),
  272. closeButton.heightAnchor.constraint(equalToConstant: 30),
  273. cardsRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  274. cardsRow.heightAnchor.constraint(equalToConstant: 420),
  275. trustRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  276. footerRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  277. crownIcon.heightAnchor.constraint(equalToConstant: 20)
  278. ])
  279. premiumCloseButton = closeButton
  280. updatePremiumCloseButtonVisibility()
  281. }
  282. private func updatePremiumCloseButtonVisibility() {
  283. premiumCloseButton?.isHidden = !subscriptionStore.isProActive
  284. }
  285. private func makePricingCard(_ plan: Plan) -> NSView {
  286. let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
  287. card.translatesAutoresizingMaskIntoConstraints = false
  288. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  289. let iconWell = NSView()
  290. iconWell.translatesAutoresizingMaskIntoConstraints = false
  291. iconWell.wantsLayer = true
  292. iconWell.layer?.cornerRadius = 10
  293. iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  294. iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
  295. iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
  296. let icon = NSImageView()
  297. icon.translatesAutoresizingMaskIntoConstraints = false
  298. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  299. icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
  300. icon.contentTintColor = plan.iconTint
  301. iconWell.addSubview(icon)
  302. NSLayoutConstraint.activate([
  303. icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
  304. icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
  305. ])
  306. let titleLabel = NSTextField(labelWithString: plan.title)
  307. titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  308. titleLabel.textColor = Theme.primaryText
  309. titleLabel.alignment = .center
  310. let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
  311. subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
  312. subtitleLabel.textColor = Theme.secondaryText
  313. subtitleLabel.alignment = .center
  314. let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
  315. topRightTag.isHidden = plan.billedPill.isEmpty
  316. topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
  317. topRightTag.heightAnchor.constraint(equalToConstant: 20).isActive = true
  318. let priceLabel = NSTextField(labelWithString: plan.price)
  319. priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
  320. priceLabel.textColor = Theme.primaryText
  321. let periodLabel = NSTextField(labelWithString: plan.period)
  322. periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
  323. periodLabel.textColor = Theme.secondaryText
  324. let priceRow = NSStackView(views: [priceLabel, periodLabel])
  325. priceRow.orientation = .horizontal
  326. priceRow.spacing = 4
  327. priceRow.alignment = .firstBaseline
  328. let billingLabel = NSTextField(labelWithString: plan.billedLine)
  329. billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
  330. billingLabel.textColor = Theme.secondaryText
  331. let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
  332. let divider = NSBox()
  333. divider.boxType = .separator
  334. divider.translatesAutoresizingMaskIntoConstraints = false
  335. divider.borderColor = Theme.divider
  336. let featuresStack = NSStackView(views: plan.features.map(makeFeatureRow(_:)))
  337. featuresStack.orientation = .vertical
  338. featuresStack.spacing = FeatureListMetrics.spacing
  339. featuresStack.alignment = .leading
  340. featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
  341. let selectButton = NSButton(title: "Get \(plan.title)", target: self, action: #selector(didTapSelectPlan))
  342. selectButton.identifier = NSUserInterfaceItemIdentifier(plan.id)
  343. planPurchaseButtons[plan.id] = selectButton
  344. planPriceFields[plan.id] = (priceLabel, periodLabel)
  345. selectButton.isBordered = false
  346. selectButton.bezelStyle = .rounded
  347. selectButton.font = .systemFont(ofSize: 14, weight: .semibold)
  348. selectButton.contentTintColor = plan.highlight ? .white : Theme.primaryText
  349. selectButton.wantsLayer = true
  350. selectButton.layer?.cornerRadius = 12
  351. selectButton.layer?.borderWidth = 1
  352. selectButton.layer?.borderColor = (plan.highlight ? Theme.accent : Theme.divider).cgColor
  353. selectButton.layer?.backgroundColor = (plan.highlight
  354. ? NSColor(srgbRed: 189 / 255, green: 52 / 255, blue: 255 / 255, alpha: 1)
  355. : Theme.mutedButtonFill).cgColor
  356. selectButton.translatesAutoresizingMaskIntoConstraints = false
  357. selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
  358. var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
  359. if !plan.billedLine.isEmpty {
  360. contentViews.append(billingLabel)
  361. }
  362. if plan.crossedPrice != nil, plan.savingsText != nil {
  363. contentViews.append(inlinePriceInfo)
  364. }
  365. contentViews.append(contentsOf: [divider, featuresStack])
  366. let verticalFlex = NSView()
  367. verticalFlex.translatesAutoresizingMaskIntoConstraints = false
  368. verticalFlex.setContentHuggingPriority(.defaultLow, for: .vertical)
  369. verticalFlex.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  370. let column = NSStackView(views: contentViews + [verticalFlex, selectButton])
  371. column.orientation = .vertical
  372. column.spacing = 10
  373. column.alignment = .centerX
  374. column.distribution = .fill
  375. column.translatesAutoresizingMaskIntoConstraints = false
  376. card.addSubview(column)
  377. card.addSubview(topRightTag)
  378. NSLayoutConstraint.activate([
  379. divider.widthAnchor.constraint(equalTo: column.widthAnchor),
  380. featuresStack.widthAnchor.constraint(equalTo: column.widthAnchor),
  381. column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  382. column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  383. column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  384. column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
  385. selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
  386. topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
  387. topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
  388. ])
  389. return card
  390. }
  391. private func makeFeatureRow(_ text: String) -> NSView {
  392. let icon = NSImageView()
  393. icon.translatesAutoresizingMaskIntoConstraints = false
  394. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  395. icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
  396. icon.contentTintColor = Theme.iconTint
  397. icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
  398. let label = NSTextField(labelWithString: text)
  399. label.font = .systemFont(ofSize: 14, weight: .medium)
  400. label.textColor = Theme.primaryText
  401. let row = NSStackView(views: [icon, label])
  402. row.orientation = .horizontal
  403. row.spacing = FeatureListMetrics.spacing
  404. row.alignment = .centerY
  405. row.distribution = .fill
  406. return row
  407. }
  408. private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
  409. guard let oldPrice, let newPrice else {
  410. return NSTextField(labelWithString: "")
  411. }
  412. let full = NSMutableAttributedString()
  413. let oldAttributes: [NSAttributedString.Key: Any] = [
  414. .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
  415. .foregroundColor: Theme.secondaryText,
  416. .strikethroughStyle: NSUnderlineStyle.single.rawValue
  417. ]
  418. let newAttributes: [NSAttributedString.Key: Any] = [
  419. .font: NSFont.systemFont(ofSize: 12, weight: .bold),
  420. .foregroundColor: Theme.successText
  421. ]
  422. full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
  423. full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
  424. let label = NSTextField(labelWithAttributedString: full)
  425. return label
  426. }
  427. private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
  428. let pill = NSTextField(labelWithString: text)
  429. pill.font = .systemFont(ofSize: 10, weight: .semibold)
  430. pill.textColor = textColor
  431. pill.alignment = .center
  432. pill.wantsLayer = true
  433. pill.layer?.backgroundColor = tint.cgColor
  434. pill.layer?.cornerRadius = 9
  435. pill.translatesAutoresizingMaskIntoConstraints = false
  436. pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
  437. pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
  438. return pill
  439. }
  440. private func makeTrustRow() -> NSView {
  441. let badges = NSStackView(views: [
  442. trustBadge(icon: "shield.fill", title: "Secure Payments", subtitle: "Your payment is 100% secure."),
  443. trustBadge(icon: "arrow.counterclockwise", title: "Cancel Anytime", subtitle: "No commitment, cancel anytime."),
  444. trustBadge(icon: "headphones", title: "24/7 Support", subtitle: "We're here to help you anytime."),
  445. trustBadge(icon: "lock.fill", title: "Privacy First", subtitle: "Your data is safe with us.")
  446. ])
  447. badges.orientation = .horizontal
  448. badges.alignment = .centerY
  449. badges.distribution = .fillEqually
  450. badges.spacing = 12
  451. badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
  452. badges.translatesAutoresizingMaskIntoConstraints = false
  453. badges.wantsLayer = true
  454. badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
  455. badges.layer?.borderColor = Theme.divider.cgColor
  456. badges.layer?.borderWidth = 1
  457. badges.layer?.cornerRadius = 10
  458. badges.setHuggingPriority(.defaultLow, for: .horizontal)
  459. badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
  460. return badges
  461. }
  462. private func makeFooterRow() -> NSView {
  463. let primary = footerActionCell(
  464. title: subscriptionPrimaryFooterTitle(),
  465. action: #selector(didTapPrimaryFooterSubscriptionAction),
  466. showsTrailingDivider: true
  467. )
  468. subscriptionPrimaryFooterButton = primary.button
  469. let entries: [(text: String, action: Selector)] = [
  470. ("Restore Purchase", #selector(didTapRestorePurchases)),
  471. ("Privacy Policy", #selector(didTapFooterPrivacyPolicy)),
  472. ("Terms of Services", #selector(didTapFooterTermsOfServices)),
  473. ("Support", #selector(didTapFooterSupport))
  474. ]
  475. let cells = [primary.container] + entries.enumerated().map { index, entry in
  476. footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
  477. }
  478. let links = NSStackView(views: cells)
  479. links.orientation = .horizontal
  480. links.distribution = .fillEqually
  481. links.spacing = 0
  482. links.alignment = .centerY
  483. links.translatesAutoresizingMaskIntoConstraints = false
  484. return links
  485. }
  486. private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
  487. let container = NSView()
  488. container.translatesAutoresizingMaskIntoConstraints = false
  489. let button = NSButton(title: title, target: self, action: action)
  490. button.isBordered = false
  491. button.bezelStyle = .rounded
  492. button.font = .systemFont(ofSize: 12, weight: .medium)
  493. button.contentTintColor = Theme.secondaryText
  494. button.focusRingType = .none
  495. button.translatesAutoresizingMaskIntoConstraints = false
  496. container.addSubview(button)
  497. var constraints: [NSLayoutConstraint] = [
  498. button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  499. button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  500. ]
  501. if showsTrailingDivider {
  502. let divider = footerDivider()
  503. container.addSubview(divider)
  504. constraints.append(contentsOf: [
  505. divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  506. divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  507. ])
  508. }
  509. NSLayoutConstraint.activate(constraints)
  510. return (container, button)
  511. }
  512. private func subscriptionPrimaryFooterTitle() -> String {
  513. subscriptionStore.isProActive ? "Manage Subscription" : "Continue with free plan"
  514. }
  515. private func updateSubscriptionPrimaryFooter() {
  516. subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
  517. }
  518. private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
  519. let image = NSImageView()
  520. image.translatesAutoresizingMaskIntoConstraints = false
  521. image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  522. image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
  523. image.contentTintColor = Theme.primaryText
  524. let titleLabel = NSTextField(labelWithString: title)
  525. titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
  526. titleLabel.textColor = Theme.primaryText
  527. let subtitleLabel = NSTextField(labelWithString: subtitle)
  528. subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
  529. subtitleLabel.textColor = Theme.secondaryText
  530. let textStack = NSStackView(views: [titleLabel, subtitleLabel])
  531. textStack.orientation = .vertical
  532. textStack.spacing = 2
  533. textStack.alignment = .leading
  534. let stack = NSStackView(views: [image, textStack])
  535. stack.orientation = .horizontal
  536. stack.spacing = 8
  537. stack.alignment = .leading
  538. stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  539. stack.wantsLayer = true
  540. stack.layer?.backgroundColor = NSColor.clear.cgColor
  541. return stack
  542. }
  543. private func footerDivider() -> NSBox {
  544. let divider = NSBox()
  545. divider.boxType = .separator
  546. divider.borderColor = Theme.divider
  547. divider.translatesAutoresizingMaskIntoConstraints = false
  548. divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
  549. divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
  550. return divider
  551. }
  552. @objc private func didTapSelectPlan(_ sender: NSButton) {
  553. guard let planKey = sender.identifier?.rawValue else { return }
  554. Task { await purchasePlan(planKey: planKey) }
  555. }
  556. @objc private func didTapPrimaryFooterSubscriptionAction() {
  557. if subscriptionStore.isProActive {
  558. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
  559. NSWorkspace.shared.open(url)
  560. } else {
  561. didTapClose()
  562. }
  563. }
  564. @objc private func didTapRestorePurchases() {
  565. Task { await restorePurchases() }
  566. }
  567. @objc private func didTapFooterPrivacyPolicy() {
  568. presentFooterPlaceholderAlert(for: "Privacy Policy")
  569. }
  570. @objc private func didTapFooterTermsOfServices() {
  571. presentFooterPlaceholderAlert(for: "Terms of Services")
  572. }
  573. @objc private func didTapFooterSupport() {
  574. presentFooterPlaceholderAlert(for: "Support")
  575. }
  576. private func presentFooterPlaceholderAlert(for featureName: String) {
  577. let alert = NSAlert()
  578. alert.messageText = "\(featureName) coming soon"
  579. alert.informativeText = "This section is a placeholder for now."
  580. alert.alertStyle = .informational
  581. alert.addButton(withTitle: "OK")
  582. if let window = view.window {
  583. alert.beginSheetModal(for: window)
  584. } else {
  585. alert.runModal()
  586. }
  587. }
  588. private func loadStoreProducts() async {
  589. await subscriptionStore.loadProducts()
  590. applyStorePricing()
  591. }
  592. private func applyStorePricing() {
  593. for plan in plans {
  594. guard let fields = planPriceFields[plan.id],
  595. let product = subscriptionStore.product(forPlanKey: plan.id) else { continue }
  596. fields.price.stringValue = product.displayPrice
  597. if let period = product.subscription?.subscriptionPeriod {
  598. fields.period.stringValue = periodSuffix(for: period)
  599. }
  600. }
  601. }
  602. private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
  603. let value = period.value
  604. switch period.unit {
  605. case .day: return value == 1 ? "/ day" : "/ \(value) days"
  606. case .week: return value == 1 ? "/ week" : "/ \(value) weeks"
  607. case .month: return value == 1 ? "/ month" : "/ \(value) months"
  608. case .year: return value == 1 ? "/ year" : "/ \(value) years"
  609. @unknown default: return ""
  610. }
  611. }
  612. private func setPurchasing(_ isPurchasing: Bool) {
  613. for button in planPurchaseButtons.values {
  614. button.isEnabled = !isPurchasing
  615. }
  616. }
  617. private func purchasePlan(planKey: String) async {
  618. setPurchasing(true)
  619. defer { setPurchasing(false) }
  620. do {
  621. let completed = try await subscriptionStore.purchase(planKey: planKey)
  622. guard completed else { return }
  623. let alert = NSAlert()
  624. alert.messageText = "You're subscribed"
  625. alert.informativeText = "Thank you — Pro features are now available."
  626. alert.alertStyle = .informational
  627. alert.addButton(withTitle: "OK")
  628. if let window = view.window {
  629. alert.beginSheetModal(for: window) { [weak self] _ in
  630. self?.dismissPremiumSheetFromParentIfNeeded()
  631. }
  632. } else {
  633. alert.runModal()
  634. dismissPremiumSheetFromParentIfNeeded()
  635. }
  636. } catch {
  637. await MainActor.run {
  638. self.presentPurchaseError(error)
  639. }
  640. }
  641. }
  642. private func restorePurchases() async {
  643. setPurchasing(true)
  644. defer { setPurchasing(false) }
  645. do {
  646. try await subscriptionStore.restorePurchases()
  647. let active = subscriptionStore.isProActive
  648. let alert = NSAlert()
  649. if active {
  650. alert.messageText = "Purchases restored"
  651. alert.informativeText = "Your subscription is active."
  652. } else {
  653. alert.messageText = "No subscription found"
  654. alert.informativeText = "There was nothing to restore for this Apple ID."
  655. }
  656. alert.alertStyle = .informational
  657. alert.addButton(withTitle: "OK")
  658. if let window = view.window {
  659. alert.beginSheetModal(for: window) { [weak self] _ in
  660. if active {
  661. self?.dismissPremiumSheetFromParentIfNeeded()
  662. }
  663. }
  664. } else {
  665. alert.runModal()
  666. if active {
  667. dismissPremiumSheetFromParentIfNeeded()
  668. }
  669. }
  670. } catch {
  671. await MainActor.run {
  672. self.presentPurchaseError(error)
  673. }
  674. }
  675. }
  676. private func presentPurchaseError(_ error: Error) {
  677. let alert = NSAlert()
  678. alert.messageText = "Something went wrong"
  679. if let localized = error as? LocalizedError {
  680. var parts: [String] = []
  681. if let description = localized.errorDescription {
  682. parts.append(description)
  683. }
  684. if let recovery = localized.recoverySuggestion {
  685. parts.append(recovery)
  686. }
  687. alert.informativeText = parts.isEmpty ? error.localizedDescription : parts.joined(separator: "\n\n")
  688. } else {
  689. alert.informativeText = error.localizedDescription
  690. }
  691. alert.alertStyle = .warning
  692. alert.addButton(withTitle: "OK")
  693. if let window = view.window {
  694. alert.beginSheetModal(for: window)
  695. } else {
  696. alert.runModal()
  697. }
  698. }
  699. private func dismissPremiumSheetFromParentIfNeeded() {
  700. guard let sheet = view.window, let parent = sheet.sheetParent else { return }
  701. parent.endSheet(sheet)
  702. }
  703. @objc private func didTapClose() {
  704. guard let window = view.window else { return }
  705. if let parent = window.sheetParent {
  706. parent.endSheet(window)
  707. return
  708. }
  709. window.close()
  710. }
  711. }