Keine Beschreibung

PremiumPlansWindowController.swift 32KB

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