Ei kuvausta

PremiumPlansWindowController.swift 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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 { @MainActor in
  204. await loadStoreProducts()
  205. }
  206. }
  207. override func viewDidLayout() {
  208. super.viewDidLayout()
  209. pageGradient.frame = view.bounds
  210. }
  211. override func loadView() {
  212. view = NSView()
  213. view.wantsLayer = true
  214. view.layer?.cornerRadius = 18
  215. view.layer?.masksToBounds = true
  216. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  217. pageGradient.startPoint = CGPoint(x: 0, y: 1)
  218. pageGradient.endPoint = CGPoint(x: 1, y: 0)
  219. view.layer?.addSublayer(pageGradient)
  220. setupLayout()
  221. }
  222. private func setupLayout() {
  223. let closeButton = NSButton(title: "", target: self, action: #selector(didTapClose))
  224. closeButton.translatesAutoresizingMaskIntoConstraints = false
  225. closeButton.isBordered = false
  226. closeButton.wantsLayer = true
  227. closeButton.layer?.cornerRadius = 15
  228. closeButton.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.92).cgColor
  229. closeButton.layer?.borderWidth = 1
  230. closeButton.layer?.borderColor = Theme.divider.cgColor
  231. closeButton.contentTintColor = Theme.secondaryText
  232. closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close")
  233. closeButton.imageScaling = .scaleProportionallyDown
  234. closeButton.bezelStyle = .regularSquare
  235. let crownIcon = NSImageView()
  236. crownIcon.translatesAutoresizingMaskIntoConstraints = false
  237. crownIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  238. crownIcon.image = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: nil)
  239. crownIcon.contentTintColor = NSColor(srgbRed: 254 / 255, green: 214 / 255, blue: 92 / 255, alpha: 1)
  240. let title = NSTextField(labelWithString: "Upgrade to Pro")
  241. title.font = .systemFont(ofSize: 40, weight: .semibold)
  242. title.textColor = Theme.primaryText
  243. title.alignment = .center
  244. let subtitle = NSTextField(labelWithString: "Unlock unlimited access to premium tools and boost your productivity.")
  245. subtitle.font = .systemFont(ofSize: 14, weight: .regular)
  246. subtitle.textColor = Theme.secondaryText
  247. subtitle.alignment = .center
  248. let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
  249. cardsRow.orientation = .horizontal
  250. cardsRow.spacing = 14
  251. cardsRow.alignment = .top
  252. cardsRow.distribution = .fillEqually
  253. cardsRow.translatesAutoresizingMaskIntoConstraints = false
  254. for card in cardsRow.arrangedSubviews {
  255. card.heightAnchor.constraint(equalTo: cardsRow.heightAnchor).isActive = true
  256. }
  257. let trustRow = makeTrustRow()
  258. let footerRow = makeFooterRow()
  259. let root = NSStackView(views: [crownIcon, title, subtitle, cardsRow, trustRow, footerRow])
  260. root.orientation = .vertical
  261. root.spacing = 18
  262. root.alignment = .centerX
  263. root.translatesAutoresizingMaskIntoConstraints = false
  264. view.addSubview(root)
  265. view.addSubview(closeButton)
  266. NSLayoutConstraint.activate([
  267. root.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  268. root.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  269. root.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
  270. root.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
  271. closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  272. closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
  273. closeButton.widthAnchor.constraint(equalToConstant: 30),
  274. closeButton.heightAnchor.constraint(equalToConstant: 30),
  275. cardsRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  276. cardsRow.heightAnchor.constraint(equalToConstant: 420),
  277. trustRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  278. footerRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  279. crownIcon.heightAnchor.constraint(equalToConstant: 20)
  280. ])
  281. premiumCloseButton = closeButton
  282. updatePremiumCloseButtonVisibility()
  283. }
  284. private func updatePremiumCloseButtonVisibility() {
  285. premiumCloseButton?.isHidden = !subscriptionStore.isProActive
  286. }
  287. private func makePricingCard(_ plan: Plan) -> NSView {
  288. let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
  289. card.translatesAutoresizingMaskIntoConstraints = false
  290. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  291. let iconWell = NSView()
  292. iconWell.translatesAutoresizingMaskIntoConstraints = false
  293. iconWell.wantsLayer = true
  294. iconWell.layer?.cornerRadius = 10
  295. iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  296. iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
  297. iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
  298. let icon = NSImageView()
  299. icon.translatesAutoresizingMaskIntoConstraints = false
  300. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  301. icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
  302. icon.contentTintColor = plan.iconTint
  303. iconWell.addSubview(icon)
  304. NSLayoutConstraint.activate([
  305. icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
  306. icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
  307. ])
  308. let titleLabel = NSTextField(labelWithString: plan.title)
  309. titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  310. titleLabel.textColor = Theme.primaryText
  311. titleLabel.alignment = .center
  312. let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
  313. subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
  314. subtitleLabel.textColor = Theme.secondaryText
  315. subtitleLabel.alignment = .center
  316. let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
  317. topRightTag.isHidden = plan.billedPill.isEmpty
  318. topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
  319. topRightTag.heightAnchor.constraint(equalToConstant: 20).isActive = true
  320. let priceLabel = NSTextField(labelWithString: plan.price)
  321. priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
  322. priceLabel.textColor = Theme.primaryText
  323. let periodLabel = NSTextField(labelWithString: plan.period)
  324. periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
  325. periodLabel.textColor = Theme.secondaryText
  326. let priceRow = NSStackView(views: [priceLabel, periodLabel])
  327. priceRow.orientation = .horizontal
  328. priceRow.spacing = 4
  329. priceRow.alignment = .firstBaseline
  330. let billingLabel = NSTextField(labelWithString: plan.billedLine)
  331. billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
  332. billingLabel.textColor = Theme.secondaryText
  333. let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
  334. let divider = NSBox()
  335. divider.boxType = .separator
  336. divider.translatesAutoresizingMaskIntoConstraints = false
  337. divider.borderColor = Theme.divider
  338. let featuresStack = NSStackView(views: plan.features.map(makeFeatureRow(_:)))
  339. featuresStack.orientation = .vertical
  340. featuresStack.spacing = FeatureListMetrics.spacing
  341. featuresStack.alignment = .leading
  342. featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
  343. let selectButton = NSButton(title: "Get \(plan.title)", target: self, action: #selector(didTapSelectPlan))
  344. selectButton.identifier = NSUserInterfaceItemIdentifier(plan.id)
  345. planPurchaseButtons[plan.id] = selectButton
  346. planPriceFields[plan.id] = (priceLabel, periodLabel)
  347. selectButton.isBordered = false
  348. selectButton.bezelStyle = .rounded
  349. selectButton.font = .systemFont(ofSize: 14, weight: .semibold)
  350. selectButton.contentTintColor = plan.highlight ? .white : Theme.primaryText
  351. selectButton.wantsLayer = true
  352. selectButton.layer?.cornerRadius = 12
  353. selectButton.layer?.borderWidth = 1
  354. selectButton.layer?.borderColor = (plan.highlight ? Theme.accent : Theme.divider).cgColor
  355. selectButton.layer?.backgroundColor = (plan.highlight
  356. ? NSColor(srgbRed: 189 / 255, green: 52 / 255, blue: 255 / 255, alpha: 1)
  357. : Theme.mutedButtonFill).cgColor
  358. selectButton.translatesAutoresizingMaskIntoConstraints = false
  359. selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
  360. var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
  361. if !plan.billedLine.isEmpty {
  362. contentViews.append(billingLabel)
  363. }
  364. if plan.crossedPrice != nil, plan.savingsText != nil {
  365. contentViews.append(inlinePriceInfo)
  366. }
  367. contentViews.append(contentsOf: [divider, featuresStack])
  368. let verticalFlex = NSView()
  369. verticalFlex.translatesAutoresizingMaskIntoConstraints = false
  370. verticalFlex.setContentHuggingPriority(.defaultLow, for: .vertical)
  371. verticalFlex.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  372. let column = NSStackView(views: contentViews + [verticalFlex, selectButton])
  373. column.orientation = .vertical
  374. column.spacing = 10
  375. column.alignment = .centerX
  376. column.distribution = .fill
  377. column.translatesAutoresizingMaskIntoConstraints = false
  378. card.addSubview(column)
  379. card.addSubview(topRightTag)
  380. NSLayoutConstraint.activate([
  381. divider.widthAnchor.constraint(equalTo: column.widthAnchor),
  382. featuresStack.widthAnchor.constraint(equalTo: column.widthAnchor),
  383. column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  384. column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  385. column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  386. column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
  387. selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
  388. topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
  389. topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
  390. ])
  391. return card
  392. }
  393. private func makeFeatureRow(_ text: String) -> NSView {
  394. let icon = NSImageView()
  395. icon.translatesAutoresizingMaskIntoConstraints = false
  396. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  397. icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
  398. icon.contentTintColor = Theme.iconTint
  399. icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
  400. let label = NSTextField(labelWithString: text)
  401. label.font = .systemFont(ofSize: 14, weight: .medium)
  402. label.textColor = Theme.primaryText
  403. let row = NSStackView(views: [icon, label])
  404. row.orientation = .horizontal
  405. row.spacing = FeatureListMetrics.spacing
  406. row.alignment = .centerY
  407. row.distribution = .fill
  408. return row
  409. }
  410. private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
  411. guard let oldPrice, let newPrice else {
  412. return NSTextField(labelWithString: "")
  413. }
  414. let full = NSMutableAttributedString()
  415. let oldAttributes: [NSAttributedString.Key: Any] = [
  416. .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
  417. .foregroundColor: Theme.secondaryText,
  418. .strikethroughStyle: NSUnderlineStyle.single.rawValue
  419. ]
  420. let newAttributes: [NSAttributedString.Key: Any] = [
  421. .font: NSFont.systemFont(ofSize: 12, weight: .bold),
  422. .foregroundColor: Theme.successText
  423. ]
  424. full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
  425. full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
  426. let label = NSTextField(labelWithAttributedString: full)
  427. return label
  428. }
  429. private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
  430. let pill = NSTextField(labelWithString: text)
  431. pill.font = .systemFont(ofSize: 10, weight: .semibold)
  432. pill.textColor = textColor
  433. pill.alignment = .center
  434. pill.wantsLayer = true
  435. pill.layer?.backgroundColor = tint.cgColor
  436. pill.layer?.cornerRadius = 9
  437. pill.translatesAutoresizingMaskIntoConstraints = false
  438. pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
  439. pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
  440. return pill
  441. }
  442. private func makeTrustRow() -> NSView {
  443. let badges = NSStackView(views: [
  444. trustBadge(icon: "shield.fill", title: "Secure Payments", subtitle: "Your payment is 100% secure."),
  445. trustBadge(icon: "arrow.counterclockwise", title: "Cancel Anytime", subtitle: "No commitment, cancel anytime."),
  446. trustBadge(icon: "headphones", title: "24/7 Support", subtitle: "We're here to help you anytime."),
  447. trustBadge(icon: "lock.fill", title: "Privacy First", subtitle: "Your data is safe with us.")
  448. ])
  449. badges.orientation = .horizontal
  450. badges.alignment = .centerY
  451. badges.distribution = .fillEqually
  452. badges.spacing = 12
  453. badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
  454. badges.translatesAutoresizingMaskIntoConstraints = false
  455. badges.wantsLayer = true
  456. badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
  457. badges.layer?.borderColor = Theme.divider.cgColor
  458. badges.layer?.borderWidth = 1
  459. badges.layer?.cornerRadius = 10
  460. badges.setHuggingPriority(.defaultLow, for: .horizontal)
  461. badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
  462. return badges
  463. }
  464. private func makeFooterRow() -> NSView {
  465. let primary = footerActionCell(
  466. title: subscriptionPrimaryFooterTitle(),
  467. action: #selector(didTapPrimaryFooterSubscriptionAction),
  468. showsTrailingDivider: true
  469. )
  470. subscriptionPrimaryFooterButton = primary.button
  471. let entries: [(text: String, action: Selector)] = [
  472. ("Restore Purchase", #selector(didTapRestorePurchases)),
  473. ("Privacy Policy", #selector(didTapFooterPrivacyPolicy)),
  474. ("Terms of Services", #selector(didTapFooterTermsOfServices)),
  475. ("Support", #selector(didTapFooterSupport))
  476. ]
  477. let cells = [primary.container] + entries.enumerated().map { index, entry in
  478. footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
  479. }
  480. let links = NSStackView(views: cells)
  481. links.orientation = .horizontal
  482. links.distribution = .fillEqually
  483. links.spacing = 0
  484. links.alignment = .centerY
  485. links.translatesAutoresizingMaskIntoConstraints = false
  486. return links
  487. }
  488. private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
  489. let container = NSView()
  490. container.translatesAutoresizingMaskIntoConstraints = false
  491. let button = NSButton(title: title, target: self, action: action)
  492. button.isBordered = false
  493. button.bezelStyle = .rounded
  494. button.font = .systemFont(ofSize: 12, weight: .medium)
  495. button.contentTintColor = Theme.secondaryText
  496. button.focusRingType = .none
  497. button.translatesAutoresizingMaskIntoConstraints = false
  498. container.addSubview(button)
  499. var constraints: [NSLayoutConstraint] = [
  500. button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  501. button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  502. ]
  503. if showsTrailingDivider {
  504. let divider = footerDivider()
  505. container.addSubview(divider)
  506. constraints.append(contentsOf: [
  507. divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  508. divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  509. ])
  510. }
  511. NSLayoutConstraint.activate(constraints)
  512. return (container, button)
  513. }
  514. private enum PrimaryFooterSubscriptionTitle {
  515. static let manage = "Manage Subscription"
  516. static let continueFree = "Continue with free plan"
  517. }
  518. private func subscriptionPrimaryFooterTitle() -> String {
  519. subscriptionStore.isProActive ? PrimaryFooterSubscriptionTitle.manage : PrimaryFooterSubscriptionTitle.continueFree
  520. }
  521. private func updateSubscriptionPrimaryFooter() {
  522. subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
  523. }
  524. private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
  525. let image = NSImageView()
  526. image.translatesAutoresizingMaskIntoConstraints = false
  527. image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  528. image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
  529. image.contentTintColor = Theme.primaryText
  530. let titleLabel = NSTextField(labelWithString: title)
  531. titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
  532. titleLabel.textColor = Theme.primaryText
  533. let subtitleLabel = NSTextField(labelWithString: subtitle)
  534. subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
  535. subtitleLabel.textColor = Theme.secondaryText
  536. let textStack = NSStackView(views: [titleLabel, subtitleLabel])
  537. textStack.orientation = .vertical
  538. textStack.spacing = 2
  539. textStack.alignment = .leading
  540. let stack = NSStackView(views: [image, textStack])
  541. stack.orientation = .horizontal
  542. stack.spacing = 8
  543. stack.alignment = .leading
  544. stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  545. stack.wantsLayer = true
  546. stack.layer?.backgroundColor = NSColor.clear.cgColor
  547. return stack
  548. }
  549. private func footerDivider() -> NSBox {
  550. let divider = NSBox()
  551. divider.boxType = .separator
  552. divider.borderColor = Theme.divider
  553. divider.translatesAutoresizingMaskIntoConstraints = false
  554. divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
  555. divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
  556. return divider
  557. }
  558. @objc private func didTapSelectPlan(_ sender: NSButton) {
  559. guard let planKey = sender.identifier?.rawValue else { return }
  560. Task { await purchasePlan(planKey: planKey) }
  561. }
  562. @objc private func didTapPrimaryFooterSubscriptionAction(_ sender: NSButton) {
  563. let userTappedManage = (sender.title == PrimaryFooterSubscriptionTitle.manage)
  564. Task { @MainActor [weak self] in
  565. guard let self else { return }
  566. await subscriptionStore.refreshEntitlements(deep: true)
  567. updateSubscriptionPrimaryFooter()
  568. let active = subscriptionStore.isProActive
  569. if active || userTappedManage {
  570. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
  571. NSWorkspace.shared.open(url)
  572. return
  573. }
  574. // Non-pro: dismiss paywall and return to the home (dashboard) window.
  575. dismissPremiumSheetFromParentIfNeeded()
  576. }
  577. }
  578. @objc private func didTapRestorePurchases() {
  579. Task { await restorePurchases() }
  580. }
  581. @objc private func didTapFooterPrivacyPolicy() {
  582. presentFooterPlaceholderAlert(for: "Privacy Policy")
  583. }
  584. @objc private func didTapFooterTermsOfServices() {
  585. presentFooterPlaceholderAlert(for: "Terms of Services")
  586. }
  587. @objc private func didTapFooterSupport() {
  588. presentFooterPlaceholderAlert(for: "Support")
  589. }
  590. private func presentFooterPlaceholderAlert(for featureName: String) {
  591. let alert = NSAlert()
  592. alert.messageText = "\(featureName) coming soon"
  593. alert.informativeText = "This section is a placeholder for now."
  594. alert.alertStyle = .informational
  595. alert.addButton(withTitle: "OK")
  596. if let window = view.window {
  597. alert.beginSheetModal(for: window)
  598. } else {
  599. alert.runModal()
  600. }
  601. }
  602. private func loadStoreProducts() async {
  603. await subscriptionStore.refreshEntitlements(deep: true)
  604. await subscriptionStore.loadProducts()
  605. applyStorePricing()
  606. updateSubscriptionPrimaryFooter()
  607. updatePremiumCloseButtonVisibility()
  608. }
  609. private func applyStorePricing() {
  610. for plan in plans {
  611. guard let fields = planPriceFields[plan.id],
  612. let product = subscriptionStore.product(forPlanKey: plan.id) else { continue }
  613. fields.price.stringValue = product.displayPrice
  614. if let period = product.subscription?.subscriptionPeriod {
  615. fields.period.stringValue = periodSuffix(for: period)
  616. }
  617. }
  618. }
  619. private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
  620. let value = period.value
  621. switch period.unit {
  622. case .day: return value == 1 ? "/ day" : "/ \(value) days"
  623. case .week: return value == 1 ? "/ week" : "/ \(value) weeks"
  624. case .month: return value == 1 ? "/ month" : "/ \(value) months"
  625. case .year: return value == 1 ? "/ year" : "/ \(value) years"
  626. @unknown default: return ""
  627. }
  628. }
  629. private func setPurchasing(_ isPurchasing: Bool) {
  630. for button in planPurchaseButtons.values {
  631. button.isEnabled = !isPurchasing
  632. }
  633. }
  634. private func purchasePlan(planKey: String) async {
  635. setPurchasing(true)
  636. defer { setPurchasing(false) }
  637. do {
  638. let completed = try await subscriptionStore.purchase(planKey: planKey)
  639. guard completed else { return }
  640. let alert = NSAlert()
  641. alert.messageText = "You're subscribed"
  642. alert.informativeText = "Thank you — Pro features are now available."
  643. alert.alertStyle = .informational
  644. alert.addButton(withTitle: "OK")
  645. if let window = view.window {
  646. alert.beginSheetModal(for: window) { [weak self] _ in
  647. self?.dismissPremiumSheetFromParentIfNeeded()
  648. }
  649. } else {
  650. alert.runModal()
  651. dismissPremiumSheetFromParentIfNeeded()
  652. }
  653. } catch {
  654. await MainActor.run {
  655. self.presentPurchaseError(error)
  656. }
  657. }
  658. }
  659. private func restorePurchases() async {
  660. setPurchasing(true)
  661. defer { setPurchasing(false) }
  662. do {
  663. try await subscriptionStore.restorePurchases()
  664. let active = subscriptionStore.isProActive
  665. let alert = NSAlert()
  666. if active {
  667. alert.messageText = "Purchases restored"
  668. alert.informativeText = "Your subscription is active."
  669. } else {
  670. alert.messageText = "No subscription found"
  671. alert.informativeText = "There was nothing to restore for this Apple ID."
  672. }
  673. alert.alertStyle = .informational
  674. alert.addButton(withTitle: "OK")
  675. if let window = view.window {
  676. alert.beginSheetModal(for: window) { [weak self] _ in
  677. if active {
  678. self?.dismissPremiumSheetFromParentIfNeeded()
  679. }
  680. }
  681. } else {
  682. alert.runModal()
  683. if active {
  684. dismissPremiumSheetFromParentIfNeeded()
  685. }
  686. }
  687. } catch {
  688. await MainActor.run {
  689. self.presentPurchaseError(error)
  690. }
  691. }
  692. }
  693. private func presentPurchaseError(_ error: Error) {
  694. let alert = NSAlert()
  695. alert.messageText = "Something went wrong"
  696. if let localized = error as? LocalizedError {
  697. var parts: [String] = []
  698. if let description = localized.errorDescription {
  699. parts.append(description)
  700. }
  701. if let recovery = localized.recoverySuggestion {
  702. parts.append(recovery)
  703. }
  704. alert.informativeText = parts.isEmpty ? error.localizedDescription : parts.joined(separator: "\n\n")
  705. } else {
  706. alert.informativeText = error.localizedDescription
  707. }
  708. alert.alertStyle = .warning
  709. alert.addButton(withTitle: "OK")
  710. if let window = view.window {
  711. alert.beginSheetModal(for: window)
  712. } else {
  713. alert.runModal()
  714. }
  715. }
  716. private func dismissPremiumSheetFromParentIfNeeded() {
  717. guard let sheet = view.window, let parent = sheet.sheetParent else { return }
  718. parent.endSheet(sheet)
  719. }
  720. @objc private func didTapClose() {
  721. guard let window = view.window else { return }
  722. if let parent = window.sheetParent {
  723. parent.endSheet(window)
  724. return
  725. }
  726. window.close()
  727. }
  728. }