Nav apraksta

PremiumPlansWindowController.swift 49KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. import Cocoa
  2. import StoreKit
  3. final class PremiumPlansWindowController: NSWindowController {
  4. /// Matches `PremiumPlansViewController.Theme.pageStart` so the window backing fills sheet corners.
  5. static var paywallSheetBackground: NSColor { PremiumPlansViewController.Theme.pageStart }
  6. init() {
  7. let viewController = PremiumPlansViewController()
  8. let window = NSWindow(contentViewController: viewController)
  9. window.title = "Premium Plans"
  10. // Borderless avoids titled-window chrome: its rounded titlebar frame often leaves dark wedges at
  11. // the corners when combined with a custom full-bleed paywall (this window is only shown as a sheet).
  12. window.styleMask = [.borderless, .closable, .resizable]
  13. window.isOpaque = true
  14. window.backgroundColor = Self.paywallSheetBackground
  15. window.setContentSize(NSSize(width: 1160, height: 760))
  16. window.minSize = NSSize(width: 980, height: 680)
  17. window.isRestorable = false
  18. window.center()
  19. super.init(window: window)
  20. }
  21. @available(*, unavailable)
  22. required init?(coder: NSCoder) {
  23. nil
  24. }
  25. }
  26. private final class PremiumPlansViewController: NSViewController {
  27. private final class HoverPricingCardView: NSView {
  28. private var baseBorderColor: NSColor
  29. private var hoverBorderColor: NSColor
  30. private var trackingAreaRef: NSTrackingArea?
  31. private var isHovered = false
  32. init(baseBorderColor: NSColor, hoverBorderColor: NSColor) {
  33. self.baseBorderColor = baseBorderColor
  34. self.hoverBorderColor = hoverBorderColor
  35. super.init(frame: .zero)
  36. wantsLayer = true
  37. layer?.cornerRadius = 16
  38. applyHoverStyle(isHovered: false, animated: false)
  39. }
  40. @available(*, unavailable)
  41. required init?(coder: NSCoder) {
  42. nil
  43. }
  44. override func updateTrackingAreas() {
  45. super.updateTrackingAreas()
  46. if let trackingAreaRef {
  47. removeTrackingArea(trackingAreaRef)
  48. }
  49. let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
  50. let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
  51. addTrackingArea(area)
  52. trackingAreaRef = area
  53. }
  54. override func mouseEntered(with event: NSEvent) {
  55. super.mouseEntered(with: event)
  56. isHovered = true
  57. applyHoverStyle(isHovered: true, animated: true)
  58. }
  59. override func mouseExited(with event: NSEvent) {
  60. super.mouseExited(with: event)
  61. isHovered = false
  62. applyHoverStyle(isHovered: false, animated: true)
  63. }
  64. func updateBorderColors(base: NSColor, hover: NSColor) {
  65. baseBorderColor = base
  66. hoverBorderColor = hover
  67. applyHoverStyle(isHovered: isHovered, animated: false)
  68. }
  69. private func applyHoverStyle(isHovered: Bool, animated: Bool) {
  70. guard let layer else { return }
  71. let updates = {
  72. layer.borderWidth = isHovered ? 2 : 1
  73. layer.borderColor = (isHovered ? self.hoverBorderColor : self.baseBorderColor).cgColor
  74. layer.shadowColor = self.hoverBorderColor.withAlphaComponent(0.35).cgColor
  75. layer.shadowOpacity = isHovered ? 0.22 : 0
  76. layer.shadowRadius = isHovered ? 14 : 0
  77. layer.shadowOffset = .init(width: 0, height: -2)
  78. }
  79. if animated {
  80. NSAnimationContext.runAnimationGroup { context in
  81. context.duration = 0.16
  82. updates()
  83. }
  84. } else {
  85. updates()
  86. }
  87. }
  88. }
  89. /// Footer text actions: accent color + pointing hand on hover (matches pricing-card tracking behavior).
  90. private final class FooterLinkButton: NSButton {
  91. private var trackingAreaRef: NSTrackingArea?
  92. private var didPushCursor = false
  93. override func updateTrackingAreas() {
  94. super.updateTrackingAreas()
  95. if let trackingAreaRef {
  96. removeTrackingArea(trackingAreaRef)
  97. }
  98. let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
  99. let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
  100. addTrackingArea(area)
  101. trackingAreaRef = area
  102. }
  103. override func mouseEntered(with event: NSEvent) {
  104. super.mouseEntered(with: event)
  105. setHoverVisuals(hovered: true)
  106. if !didPushCursor {
  107. NSCursor.pointingHand.push()
  108. didPushCursor = true
  109. }
  110. }
  111. override func mouseExited(with event: NSEvent) {
  112. super.mouseExited(with: event)
  113. setHoverVisuals(hovered: false)
  114. if didPushCursor {
  115. NSCursor.pop()
  116. didPushCursor = false
  117. }
  118. }
  119. override func viewWillMove(toWindow newWindow: NSWindow?) {
  120. super.viewWillMove(toWindow: newWindow)
  121. if newWindow == nil, didPushCursor {
  122. NSCursor.pop()
  123. didPushCursor = false
  124. }
  125. if newWindow == nil {
  126. setHoverVisuals(hovered: false, animated: false)
  127. }
  128. }
  129. private func setHoverVisuals(hovered: Bool, animated: Bool = true) {
  130. let color = hovered ? Theme.accent : Theme.secondaryText
  131. if animated {
  132. NSAnimationContext.runAnimationGroup { context in
  133. context.duration = 0.15
  134. self.animator().contentTintColor = color
  135. }
  136. } else {
  137. contentTintColor = color
  138. }
  139. }
  140. }
  141. /// Purchase CTAs: fill/border/shadow + pointing hand on hover.
  142. private final class PlanPurchaseHoverButton: NSButton {
  143. private var trackingAreaRef: NSTrackingArea?
  144. private var didPushCursor = false
  145. private let isPrimaryStyle: Bool
  146. private static let primaryFill = NSColor(srgbRed: 189 / 255, green: 52 / 255, blue: 255 / 255, alpha: 1)
  147. private static let primaryFillHover = NSColor(srgbRed: 205 / 255, green: 88 / 255, blue: 255 / 255, alpha: 1)
  148. init(planId: String, title: String, isPrimaryStyle: Bool, target: AnyObject?, action: Selector) {
  149. self.isPrimaryStyle = isPrimaryStyle
  150. super.init(frame: .zero)
  151. identifier = NSUserInterfaceItemIdentifier(planId)
  152. self.title = title
  153. self.target = target
  154. self.action = action
  155. isBordered = false
  156. bezelStyle = .rounded
  157. font = .systemFont(ofSize: 14, weight: .semibold)
  158. wantsLayer = true
  159. layer?.cornerRadius = 12
  160. focusRingType = .none
  161. translatesAutoresizingMaskIntoConstraints = false
  162. applyBaseStyle(hovered: false)
  163. }
  164. @available(*, unavailable)
  165. required init?(coder: NSCoder) {
  166. nil
  167. }
  168. override var isEnabled: Bool {
  169. didSet {
  170. if !isEnabled {
  171. applyBaseStyle(hovered: false, animated: true)
  172. if didPushCursor {
  173. NSCursor.pop()
  174. didPushCursor = false
  175. }
  176. }
  177. }
  178. }
  179. override func updateTrackingAreas() {
  180. super.updateTrackingAreas()
  181. if let trackingAreaRef {
  182. removeTrackingArea(trackingAreaRef)
  183. }
  184. let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
  185. let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
  186. addTrackingArea(area)
  187. trackingAreaRef = area
  188. }
  189. override func mouseEntered(with event: NSEvent) {
  190. super.mouseEntered(with: event)
  191. guard isEnabled else { return }
  192. applyBaseStyle(hovered: true, animated: true)
  193. if !didPushCursor {
  194. NSCursor.pointingHand.push()
  195. didPushCursor = true
  196. }
  197. }
  198. override func mouseExited(with event: NSEvent) {
  199. super.mouseExited(with: event)
  200. applyBaseStyle(hovered: false, animated: true)
  201. if didPushCursor {
  202. NSCursor.pop()
  203. didPushCursor = false
  204. }
  205. }
  206. override func viewWillMove(toWindow newWindow: NSWindow?) {
  207. super.viewWillMove(toWindow: newWindow)
  208. if newWindow == nil, didPushCursor {
  209. NSCursor.pop()
  210. didPushCursor = false
  211. }
  212. if newWindow == nil {
  213. applyBaseStyle(hovered: false, animated: false)
  214. }
  215. }
  216. func refreshAppearance() {
  217. applyBaseStyle(hovered: false, animated: false)
  218. }
  219. private func applyBaseStyle(hovered: Bool, animated: Bool = true) {
  220. let updates = {
  221. if self.isPrimaryStyle {
  222. self.layer?.backgroundColor = (hovered ? Self.primaryFillHover : Self.primaryFill).cgColor
  223. self.layer?.borderColor = Theme.accent.cgColor
  224. self.layer?.borderWidth = hovered ? 2 : 1
  225. self.contentTintColor = .white
  226. self.layer?.shadowColor = Self.primaryFill.cgColor
  227. self.layer?.shadowOpacity = hovered ? 0.28 : 0
  228. self.layer?.shadowRadius = hovered ? 12 : 0
  229. self.layer?.shadowOffset = CGSize(width: 0, height: -2)
  230. } else {
  231. let baseFill = Theme.mutedButtonFill
  232. let hoverFill = baseFill.blended(withFraction: 0.22, of: Theme.accent) ?? baseFill
  233. self.layer?.backgroundColor = (hovered ? hoverFill : baseFill).cgColor
  234. self.layer?.borderColor = (hovered ? Theme.accent : Theme.divider).cgColor
  235. self.layer?.borderWidth = hovered ? 2 : 1
  236. self.contentTintColor = Theme.primaryText
  237. self.layer?.shadowColor = Theme.accent.withAlphaComponent(0.35).cgColor
  238. self.layer?.shadowOpacity = hovered ? 0.18 : 0
  239. self.layer?.shadowRadius = hovered ? 10 : 0
  240. self.layer?.shadowOffset = CGSize(width: 0, height: -2)
  241. }
  242. }
  243. if animated {
  244. NSAnimationContext.runAnimationGroup { context in
  245. context.duration = 0.16
  246. updates()
  247. }
  248. } else {
  249. updates()
  250. }
  251. }
  252. }
  253. /// Close control: subtle lift + accent tint on hover.
  254. private final class PremiumCloseHoverButton: NSButton {
  255. private var trackingAreaRef: NSTrackingArea?
  256. private var didPushCursor = false
  257. init(target: AnyObject?, action: Selector) {
  258. super.init(frame: .zero)
  259. self.target = target
  260. self.action = action
  261. isBordered = false
  262. wantsLayer = true
  263. layer?.cornerRadius = 15
  264. bezelStyle = .regularSquare
  265. image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close")
  266. imageScaling = .scaleProportionallyDown
  267. focusRingType = .none
  268. translatesAutoresizingMaskIntoConstraints = false
  269. applyStyle(hovered: false, animated: false)
  270. }
  271. @available(*, unavailable)
  272. required init?(coder: NSCoder) {
  273. nil
  274. }
  275. override func updateTrackingAreas() {
  276. super.updateTrackingAreas()
  277. if let trackingAreaRef {
  278. removeTrackingArea(trackingAreaRef)
  279. }
  280. let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
  281. let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
  282. addTrackingArea(area)
  283. trackingAreaRef = area
  284. }
  285. override func mouseEntered(with event: NSEvent) {
  286. super.mouseEntered(with: event)
  287. applyStyle(hovered: true, animated: true)
  288. if !didPushCursor {
  289. NSCursor.pointingHand.push()
  290. didPushCursor = true
  291. }
  292. }
  293. override func mouseExited(with event: NSEvent) {
  294. super.mouseExited(with: event)
  295. applyStyle(hovered: false, animated: true)
  296. if didPushCursor {
  297. NSCursor.pop()
  298. didPushCursor = false
  299. }
  300. }
  301. override func viewWillMove(toWindow newWindow: NSWindow?) {
  302. super.viewWillMove(toWindow: newWindow)
  303. if newWindow == nil, didPushCursor {
  304. NSCursor.pop()
  305. didPushCursor = false
  306. }
  307. if newWindow == nil {
  308. applyStyle(hovered: false, animated: false)
  309. }
  310. }
  311. func refreshAppearance(hovered: Bool) {
  312. applyStyle(hovered: hovered, animated: false)
  313. }
  314. private func applyStyle(hovered: Bool, animated: Bool) {
  315. let updates = {
  316. self.layer?.backgroundColor = (hovered
  317. ? Theme.closeButtonBackgroundHover
  318. : Theme.closeButtonBackground).cgColor
  319. self.layer?.borderColor = (hovered ? Theme.accent.withAlphaComponent(0.45) : Theme.divider).cgColor
  320. self.layer?.borderWidth = hovered ? 1.5 : 1
  321. self.contentTintColor = hovered ? Theme.accent : Theme.secondaryText
  322. self.layer?.shadowColor = Theme.accent.withAlphaComponent(0.25).cgColor
  323. self.layer?.shadowOpacity = hovered ? 0.2 : 0
  324. self.layer?.shadowRadius = hovered ? 8 : 0
  325. self.layer?.shadowOffset = CGSize(width: 0, height: -1)
  326. }
  327. if animated {
  328. NSAnimationContext.runAnimationGroup { context in
  329. context.duration = 0.15
  330. updates()
  331. }
  332. } else {
  333. updates()
  334. }
  335. }
  336. }
  337. /// Shown until StoreKit returns localized `Product.displayPrice` (never use hardcoded currency amounts).
  338. private static let unloadedPricePlaceholder = "—"
  339. private struct Plan {
  340. let id: String
  341. let title: String
  342. let subtitle: String
  343. let period: String
  344. let billedPill: String
  345. let billedLine: String
  346. let crossedPrice: String?
  347. let savingsText: String?
  348. let features: [String]
  349. let iconName: String
  350. let iconTint: NSColor
  351. let highlight: Bool
  352. }
  353. fileprivate enum Theme {
  354. static var pageStart: NSColor {
  355. AppDashboardTheme.isDark
  356. ? AppDashboardTheme.pageBackground
  357. : NSColor(srgbRed: 249 / 255, green: 252 / 255, blue: 255 / 255, alpha: 1)
  358. }
  359. static var pageEnd: NSColor {
  360. AppDashboardTheme.isDark
  361. ? AppDashboardTheme.loadingPageBackgroundBottom
  362. : NSColor(srgbRed: 238 / 255, green: 244 / 255, blue: 255 / 255, alpha: 1)
  363. }
  364. static var cardBackground: NSColor { AppDashboardTheme.cardBackground }
  365. static var primaryText: NSColor {
  366. AppDashboardTheme.isDark
  367. ? AppDashboardTheme.primaryText
  368. : NSColor(srgbRed: 27 / 255, green: 38 / 255, blue: 79 / 255, alpha: 1)
  369. }
  370. static var secondaryText: NSColor {
  371. AppDashboardTheme.isDark
  372. ? AppDashboardTheme.secondaryText
  373. : NSColor(srgbRed: 108 / 255, green: 120 / 255, blue: 157 / 255, alpha: 1)
  374. }
  375. static var cardBorder: NSColor {
  376. AppDashboardTheme.isDark
  377. ? AppDashboardTheme.border
  378. : NSColor(srgbRed: 198 / 255, green: 216 / 255, blue: 255 / 255, alpha: 1)
  379. }
  380. static var accent: NSColor { AppDashboardTheme.brandBlue }
  381. static var accentHover: NSColor { AppDashboardTheme.brandBlueHover }
  382. static var mutedButtonFill: NSColor {
  383. AppDashboardTheme.isDark
  384. ? AppDashboardTheme.profileFieldFill
  385. : NSColor(srgbRed: 238 / 255, green: 243 / 255, blue: 252 / 255, alpha: 1)
  386. }
  387. static var bottomStrip: NSColor {
  388. AppDashboardTheme.isDark
  389. ? AppDashboardTheme.proCardFill
  390. : NSColor(srgbRed: 244 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1)
  391. }
  392. static var divider: NSColor {
  393. AppDashboardTheme.isDark
  394. ? AppDashboardTheme.border
  395. : NSColor(srgbRed: 218 / 255, green: 228 / 255, blue: 247 / 255, alpha: 1)
  396. }
  397. static var successText: NSColor {
  398. AppDashboardTheme.isDark
  399. ? AppDashboardTheme.welcomeHeroHeadingBlue
  400. : NSColor(srgbRed: 21 / 255, green: 154 / 255, blue: 220 / 255, alpha: 1)
  401. }
  402. static var iconTint: NSColor { AppDashboardTheme.brandBlue }
  403. static var closeButtonBackground: NSColor {
  404. AppDashboardTheme.isDark
  405. ? AppDashboardTheme.cardBackground
  406. : NSColor.white.withAlphaComponent(0.92)
  407. }
  408. static var closeButtonBackgroundHover: NSColor {
  409. AppDashboardTheme.isDark
  410. ? AppDashboardTheme.neutralHoverFill
  411. : NSColor.white.withAlphaComponent(0.98)
  412. }
  413. }
  414. private struct PricingCardAppearanceTarget {
  415. let card: HoverPricingCardView
  416. let iconWell: NSView
  417. let planIconView: NSImageView
  418. let planId: String
  419. let titleLabel: NSTextField
  420. let subtitleLabel: NSTextField
  421. let priceLabel: NSTextField
  422. let periodLabel: NSTextField
  423. let billingLabel: NSTextField?
  424. let divider: NSBox
  425. let featureLabels: [NSTextField]
  426. let featureIcons: [NSImageView]
  427. let purchaseButton: PlanPurchaseHoverButton
  428. }
  429. private enum FeatureListMetrics {
  430. static let spacing = CGFloat(10)
  431. static let edgeInsets = NSEdgeInsets(top: 21, left: 37, bottom: 21, right: 0)
  432. }
  433. private let subscriptionStore = SubscriptionStore.shared
  434. private var planPriceFields: [String: (price: NSTextField, period: NSTextField)] = [:]
  435. private var planPurchaseButtons: [String: NSButton] = [:]
  436. private var subscriptionPrimaryFooterButton: NSButton?
  437. private var premiumCloseButton: PremiumCloseHoverButton?
  438. private var subscriptionStatusObservation: NSObjectProtocol?
  439. private var appearanceObserver: NSObjectProtocol?
  440. private let plans: [Plan] = [
  441. Plan(
  442. id: "weekly",
  443. title: "Weekly",
  444. subtitle: "Flexible and commitment-free",
  445. period: "/ week",
  446. billedPill: "",
  447. billedLine: "",
  448. crossedPrice: nil,
  449. savingsText: nil,
  450. features: [
  451. "All premium features",
  452. "Perfect for short-term goals",
  453. "Cancel anytime"
  454. ],
  455. iconName: "paperplane.fill",
  456. iconTint: Theme.iconTint,
  457. highlight: false
  458. ),
  459. Plan(
  460. id: "monthly",
  461. title: "Monthly",
  462. subtitle: "Balanced for regular productivity",
  463. period: "/ month",
  464. billedPill: "",
  465. billedLine: "",
  466. crossedPrice: nil,
  467. savingsText: nil,
  468. features: [
  469. "All premium features",
  470. "Best value for regular users",
  471. "Priority support"
  472. ],
  473. iconName: "bolt.fill",
  474. iconTint: Theme.accent,
  475. highlight: true
  476. ),
  477. Plan(
  478. id: "yearly",
  479. title: "Yearly",
  480. subtitle: "Best value for long-term users",
  481. period: "/ year",
  482. billedPill: "3 days free trial",
  483. billedLine: "",
  484. crossedPrice: nil,
  485. savingsText: nil,
  486. features: [
  487. "All premium features",
  488. "Lowest effective monthly cost",
  489. "Ideal for long-term use"
  490. ],
  491. iconName: "crown.fill",
  492. iconTint: Theme.successText,
  493. highlight: false
  494. )
  495. ]
  496. private let pageGradient = CAGradientLayer()
  497. private var premiumTitleLabel: NSTextField?
  498. private var premiumSubtitleLabel: NSTextField?
  499. private var pricingCardTargets: [PricingCardAppearanceTarget] = []
  500. private weak var trustBadgesRow: NSStackView?
  501. private var footerLinkButtons: [FooterLinkButton] = []
  502. deinit {
  503. if let subscriptionStatusObservation {
  504. NotificationCenter.default.removeObserver(subscriptionStatusObservation)
  505. }
  506. if let appearanceObserver {
  507. NotificationCenter.default.removeObserver(appearanceObserver)
  508. }
  509. }
  510. override func viewDidLoad() {
  511. super.viewDidLoad()
  512. appearanceObserver = NotificationCenter.default.addObserver(
  513. forName: AppAppearanceManager.didChangeNotification,
  514. object: nil,
  515. queue: .main
  516. ) { [weak self] _ in
  517. self?.applyCurrentAppearance()
  518. }
  519. subscriptionStatusObservation = NotificationCenter.default.addObserver(
  520. forName: .subscriptionStatusDidChange,
  521. object: nil,
  522. queue: .main
  523. ) { [weak self] _ in
  524. Task { @MainActor in
  525. await self?.subscriptionStore.loadProducts()
  526. self?.applyStorePricing()
  527. self?.updateSubscriptionPrimaryFooter()
  528. self?.updatePremiumCloseButtonVisibility()
  529. }
  530. }
  531. Task { @MainActor in
  532. await loadStoreProducts()
  533. }
  534. }
  535. override func viewDidLayout() {
  536. super.viewDidLayout()
  537. pageGradient.frame = view.bounds
  538. }
  539. override func loadView() {
  540. view = NSView()
  541. view.wantsLayer = true
  542. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  543. pageGradient.startPoint = CGPoint(x: 0, y: 1)
  544. pageGradient.endPoint = CGPoint(x: 1, y: 0)
  545. view.layer?.addSublayer(pageGradient)
  546. setupLayout()
  547. applyCurrentAppearance()
  548. }
  549. private func setupLayout() {
  550. let closeButton = PremiumCloseHoverButton(target: self, action: #selector(didTapClose))
  551. let crownIcon = NSImageView()
  552. crownIcon.translatesAutoresizingMaskIntoConstraints = false
  553. crownIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  554. crownIcon.image = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: nil)
  555. crownIcon.contentTintColor = NSColor(srgbRed: 254 / 255, green: 214 / 255, blue: 92 / 255, alpha: 1)
  556. let title = NSTextField(labelWithString: "Upgrade to Pro")
  557. title.font = .systemFont(ofSize: 40, weight: .semibold)
  558. title.textColor = Theme.primaryText
  559. title.alignment = .center
  560. premiumTitleLabel = title
  561. let subtitle = NSTextField(labelWithString: "Unlock unlimited access to premium tools and boost your productivity.")
  562. subtitle.font = .systemFont(ofSize: 14, weight: .regular)
  563. subtitle.textColor = Theme.secondaryText
  564. subtitle.alignment = .center
  565. premiumSubtitleLabel = subtitle
  566. pricingCardTargets = []
  567. let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
  568. cardsRow.orientation = .horizontal
  569. cardsRow.spacing = 14
  570. cardsRow.alignment = .top
  571. cardsRow.distribution = .fillEqually
  572. cardsRow.translatesAutoresizingMaskIntoConstraints = false
  573. for card in cardsRow.arrangedSubviews {
  574. card.heightAnchor.constraint(equalTo: cardsRow.heightAnchor).isActive = true
  575. }
  576. let trustRow = makeTrustRow()
  577. let footerRow = makeFooterRow()
  578. let root = NSStackView(views: [crownIcon, title, subtitle, cardsRow, trustRow, footerRow])
  579. root.orientation = .vertical
  580. root.spacing = 18
  581. root.alignment = .centerX
  582. root.translatesAutoresizingMaskIntoConstraints = false
  583. view.addSubview(root)
  584. view.addSubview(closeButton)
  585. NSLayoutConstraint.activate([
  586. root.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  587. root.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  588. root.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
  589. root.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
  590. closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  591. closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
  592. closeButton.widthAnchor.constraint(equalToConstant: 30),
  593. closeButton.heightAnchor.constraint(equalToConstant: 30),
  594. cardsRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  595. cardsRow.heightAnchor.constraint(equalToConstant: 420),
  596. trustRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  597. footerRow.widthAnchor.constraint(equalTo: root.widthAnchor),
  598. crownIcon.heightAnchor.constraint(equalToConstant: 20)
  599. ])
  600. premiumCloseButton = closeButton
  601. updatePremiumCloseButtonVisibility()
  602. }
  603. private func updatePremiumCloseButtonVisibility() {
  604. premiumCloseButton?.isHidden = !subscriptionStore.isProActive
  605. }
  606. private func makePricingCard(_ plan: Plan) -> NSView {
  607. let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
  608. card.translatesAutoresizingMaskIntoConstraints = false
  609. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  610. let iconWell = NSView()
  611. iconWell.translatesAutoresizingMaskIntoConstraints = false
  612. iconWell.wantsLayer = true
  613. iconWell.layer?.cornerRadius = 10
  614. iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  615. iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
  616. iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
  617. let icon = NSImageView()
  618. icon.translatesAutoresizingMaskIntoConstraints = false
  619. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  620. icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
  621. icon.contentTintColor = plan.iconTint
  622. iconWell.addSubview(icon)
  623. NSLayoutConstraint.activate([
  624. icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
  625. icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
  626. ])
  627. let titleLabel = NSTextField(labelWithString: plan.title)
  628. titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  629. titleLabel.textColor = Theme.primaryText
  630. titleLabel.alignment = .center
  631. let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
  632. subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
  633. subtitleLabel.textColor = Theme.secondaryText
  634. subtitleLabel.alignment = .center
  635. let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
  636. topRightTag.isHidden = plan.billedPill.isEmpty
  637. topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
  638. let priceLabel = NSTextField(labelWithString: Self.unloadedPricePlaceholder)
  639. priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
  640. priceLabel.textColor = Theme.primaryText
  641. let periodLabel = NSTextField(labelWithString: plan.period)
  642. periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
  643. periodLabel.textColor = Theme.secondaryText
  644. let priceRow = NSStackView(views: [priceLabel, periodLabel])
  645. priceRow.orientation = .horizontal
  646. priceRow.spacing = 4
  647. priceRow.alignment = .firstBaseline
  648. let billingLabel = NSTextField(labelWithString: plan.billedLine)
  649. billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
  650. billingLabel.textColor = Theme.secondaryText
  651. let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
  652. let divider = NSBox()
  653. divider.boxType = .separator
  654. divider.translatesAutoresizingMaskIntoConstraints = false
  655. divider.borderColor = Theme.divider
  656. let featureRows = plan.features.map(makeFeatureRow(_:))
  657. let featuresStack = NSStackView(views: featureRows)
  658. featuresStack.orientation = .vertical
  659. featuresStack.spacing = FeatureListMetrics.spacing
  660. featuresStack.alignment = .leading
  661. featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
  662. let selectButton = PlanPurchaseHoverButton(
  663. planId: plan.id,
  664. title: "Get \(plan.title)",
  665. isPrimaryStyle: plan.highlight,
  666. target: self,
  667. action: #selector(didTapSelectPlan)
  668. )
  669. planPurchaseButtons[plan.id] = selectButton
  670. planPriceFields[plan.id] = (priceLabel, periodLabel)
  671. selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
  672. let featureLabels = featureRows.compactMap { row -> NSTextField? in
  673. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSTextField }.first
  674. }
  675. let featureIcons = featureRows.compactMap { row -> NSImageView? in
  676. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSImageView }.first
  677. }
  678. pricingCardTargets.append(
  679. PricingCardAppearanceTarget(
  680. card: card,
  681. iconWell: iconWell,
  682. planIconView: icon,
  683. planId: plan.id,
  684. titleLabel: titleLabel,
  685. subtitleLabel: subtitleLabel,
  686. priceLabel: priceLabel,
  687. periodLabel: periodLabel,
  688. billingLabel: plan.billedLine.isEmpty ? nil : billingLabel,
  689. divider: divider,
  690. featureLabels: featureLabels,
  691. featureIcons: featureIcons,
  692. purchaseButton: selectButton
  693. )
  694. )
  695. var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
  696. if !plan.billedLine.isEmpty {
  697. contentViews.append(billingLabel)
  698. }
  699. if plan.crossedPrice != nil, plan.savingsText != nil {
  700. contentViews.append(inlinePriceInfo)
  701. }
  702. contentViews.append(contentsOf: [divider, featuresStack])
  703. let verticalFlex = NSView()
  704. verticalFlex.translatesAutoresizingMaskIntoConstraints = false
  705. verticalFlex.setContentHuggingPriority(.defaultLow, for: .vertical)
  706. verticalFlex.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  707. let column = NSStackView(views: contentViews + [verticalFlex, selectButton])
  708. column.orientation = .vertical
  709. column.spacing = 10
  710. column.alignment = .centerX
  711. column.distribution = .fill
  712. column.translatesAutoresizingMaskIntoConstraints = false
  713. card.addSubview(column)
  714. card.addSubview(topRightTag)
  715. NSLayoutConstraint.activate([
  716. divider.widthAnchor.constraint(equalTo: column.widthAnchor),
  717. featuresStack.widthAnchor.constraint(equalTo: column.widthAnchor),
  718. column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  719. column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  720. column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  721. column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
  722. selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
  723. topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
  724. topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
  725. ])
  726. return card
  727. }
  728. private func makeFeatureRow(_ text: String) -> NSView {
  729. let icon = NSImageView()
  730. icon.translatesAutoresizingMaskIntoConstraints = false
  731. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  732. icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
  733. icon.contentTintColor = Theme.iconTint
  734. icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
  735. let label = NSTextField(labelWithString: text)
  736. label.font = .systemFont(ofSize: 14, weight: .medium)
  737. label.textColor = Theme.primaryText
  738. let row = NSStackView(views: [icon, label])
  739. row.orientation = .horizontal
  740. row.spacing = FeatureListMetrics.spacing
  741. row.alignment = .centerY
  742. row.distribution = .fill
  743. return row
  744. }
  745. private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
  746. guard let oldPrice, let newPrice else {
  747. return NSTextField(labelWithString: "")
  748. }
  749. let full = NSMutableAttributedString()
  750. let oldAttributes: [NSAttributedString.Key: Any] = [
  751. .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
  752. .foregroundColor: Theme.secondaryText,
  753. .strikethroughStyle: NSUnderlineStyle.single.rawValue
  754. ]
  755. let newAttributes: [NSAttributedString.Key: Any] = [
  756. .font: NSFont.systemFont(ofSize: 12, weight: .bold),
  757. .foregroundColor: Theme.successText
  758. ]
  759. full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
  760. full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
  761. let label = NSTextField(labelWithAttributedString: full)
  762. return label
  763. }
  764. private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
  765. let pill = NSTextField(labelWithString: text)
  766. pill.font = .systemFont(ofSize: 10, weight: .semibold)
  767. pill.textColor = textColor
  768. pill.alignment = .center
  769. pill.wantsLayer = true
  770. pill.layer?.backgroundColor = tint.cgColor
  771. pill.layer?.cornerRadius = 9
  772. pill.translatesAutoresizingMaskIntoConstraints = false
  773. pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
  774. pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
  775. return pill
  776. }
  777. private func makeTrustRow() -> NSView {
  778. let badges = NSStackView(views: [
  779. trustBadge(icon: "shield.fill", title: "Secure Payments", subtitle: "Your payment is 100% secure."),
  780. trustBadge(icon: "arrow.counterclockwise", title: "Cancel Anytime", subtitle: "No commitment, cancel anytime."),
  781. trustBadge(icon: "headphones", title: "24/7 Support", subtitle: "We're here to help you anytime."),
  782. trustBadge(icon: "lock.fill", title: "Privacy First", subtitle: "Your data is safe with us.")
  783. ])
  784. badges.orientation = .horizontal
  785. badges.alignment = .centerY
  786. badges.distribution = .fillEqually
  787. badges.spacing = 12
  788. badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
  789. badges.translatesAutoresizingMaskIntoConstraints = false
  790. badges.wantsLayer = true
  791. badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
  792. badges.layer?.borderColor = Theme.divider.cgColor
  793. badges.layer?.borderWidth = 1
  794. badges.layer?.cornerRadius = 10
  795. badges.setHuggingPriority(.defaultLow, for: .horizontal)
  796. badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
  797. trustBadgesRow = badges
  798. return badges
  799. }
  800. private func makeFooterRow() -> NSView {
  801. footerLinkButtons = []
  802. let primary = footerActionCell(
  803. title: subscriptionPrimaryFooterTitle(),
  804. action: #selector(didTapPrimaryFooterSubscriptionAction),
  805. showsTrailingDivider: true
  806. )
  807. subscriptionPrimaryFooterButton = primary.button
  808. let entries: [(text: String, action: Selector)] = [
  809. ("Restore Purchase", #selector(didTapRestorePurchases)),
  810. ("Privacy Policy", #selector(didTapFooterPrivacyPolicy)),
  811. ("Terms of Use", #selector(didTapFooterTermsOfServices)),
  812. ("Support", #selector(didTapFooterSupport))
  813. ]
  814. let cells = [primary.container] + entries.enumerated().map { index, entry in
  815. footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
  816. }
  817. let links = NSStackView(views: cells)
  818. links.orientation = .horizontal
  819. links.distribution = .fillEqually
  820. links.spacing = 0
  821. links.alignment = .centerY
  822. links.translatesAutoresizingMaskIntoConstraints = false
  823. return links
  824. }
  825. private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
  826. let container = NSView()
  827. container.translatesAutoresizingMaskIntoConstraints = false
  828. let button = FooterLinkButton(title: title, target: self, action: action)
  829. button.isBordered = false
  830. button.bezelStyle = .rounded
  831. button.font = .systemFont(ofSize: 12, weight: .medium)
  832. button.contentTintColor = Theme.secondaryText
  833. button.focusRingType = .none
  834. button.translatesAutoresizingMaskIntoConstraints = false
  835. footerLinkButtons.append(button)
  836. container.addSubview(button)
  837. var constraints: [NSLayoutConstraint] = [
  838. button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  839. button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  840. ]
  841. if showsTrailingDivider {
  842. let divider = footerDivider()
  843. container.addSubview(divider)
  844. constraints.append(contentsOf: [
  845. divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  846. divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  847. ])
  848. }
  849. NSLayoutConstraint.activate(constraints)
  850. return (container, button)
  851. }
  852. private enum PrimaryFooterSubscriptionTitle {
  853. static let manage = "Manage Subscription"
  854. static let continueFree = "Continue with free plan"
  855. }
  856. private func subscriptionPrimaryFooterTitle() -> String {
  857. subscriptionStore.isProActive ? PrimaryFooterSubscriptionTitle.manage : PrimaryFooterSubscriptionTitle.continueFree
  858. }
  859. private func updateSubscriptionPrimaryFooter() {
  860. subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
  861. }
  862. private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
  863. let image = NSImageView()
  864. image.translatesAutoresizingMaskIntoConstraints = false
  865. image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  866. image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
  867. image.contentTintColor = Theme.primaryText
  868. let titleLabel = NSTextField(labelWithString: title)
  869. titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
  870. titleLabel.textColor = Theme.primaryText
  871. let subtitleLabel = NSTextField(labelWithString: subtitle)
  872. subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
  873. subtitleLabel.textColor = Theme.secondaryText
  874. let textStack = NSStackView(views: [titleLabel, subtitleLabel])
  875. textStack.orientation = .vertical
  876. textStack.spacing = 2
  877. textStack.alignment = .leading
  878. let stack = NSStackView(views: [image, textStack])
  879. stack.orientation = .horizontal
  880. stack.spacing = 8
  881. stack.alignment = .leading
  882. stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  883. stack.wantsLayer = true
  884. stack.layer?.backgroundColor = NSColor.clear.cgColor
  885. return stack
  886. }
  887. private func footerDivider() -> NSBox {
  888. let divider = NSBox()
  889. divider.boxType = .separator
  890. divider.borderColor = Theme.divider
  891. divider.translatesAutoresizingMaskIntoConstraints = false
  892. divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
  893. divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
  894. return divider
  895. }
  896. @objc private func didTapSelectPlan(_ sender: NSButton) {
  897. guard let planKey = sender.identifier?.rawValue else { return }
  898. Task { await purchasePlan(planKey: planKey) }
  899. }
  900. @objc private func didTapPrimaryFooterSubscriptionAction(_ sender: NSButton) {
  901. let userTappedManage = (sender.title == PrimaryFooterSubscriptionTitle.manage)
  902. Task { @MainActor [weak self] in
  903. guard let self else { return }
  904. await subscriptionStore.refreshEntitlements(deep: true)
  905. updateSubscriptionPrimaryFooter()
  906. let active = subscriptionStore.isProActive
  907. if active || userTappedManage {
  908. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
  909. NSWorkspace.shared.open(url)
  910. return
  911. }
  912. // Non-pro: dismiss paywall and return to the home (dashboard) window.
  913. dismissPremiumSheetFromParentIfNeeded()
  914. }
  915. }
  916. @objc private func didTapRestorePurchases() {
  917. Task { await restorePurchases() }
  918. }
  919. @objc private func didTapFooterPrivacyPolicy() {
  920. AppLegalURLs.openInSafari(AppLegalURLs.privacyPolicy)
  921. }
  922. @objc private func didTapFooterTermsOfServices() {
  923. AppLegalURLs.openInSafari(AppLegalURLs.termsOfUse)
  924. }
  925. @objc private func didTapFooterSupport() {
  926. AppLegalURLs.openInSafari(AppLegalURLs.support)
  927. }
  928. private func loadStoreProducts() async {
  929. await subscriptionStore.refreshEntitlements(deep: true)
  930. await subscriptionStore.loadProducts()
  931. applyStorePricing()
  932. updateSubscriptionPrimaryFooter()
  933. updatePremiumCloseButtonVisibility()
  934. }
  935. private func applyStorePricing() {
  936. for plan in plans {
  937. guard let fields = planPriceFields[plan.id] else { continue }
  938. guard let product = subscriptionStore.product(forPlanKey: plan.id) else {
  939. fields.price.stringValue = Self.unloadedPricePlaceholder
  940. continue
  941. }
  942. fields.price.stringValue = product.displayPrice
  943. if let period = product.subscription?.subscriptionPeriod {
  944. fields.period.stringValue = periodSuffix(for: period)
  945. }
  946. }
  947. }
  948. private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
  949. let value = period.value
  950. switch period.unit {
  951. case .day: return value == 1 ? "/ day" : "/ \(value) days"
  952. case .week: return value == 1 ? "/ week" : "/ \(value) weeks"
  953. case .month: return value == 1 ? "/ month" : "/ \(value) months"
  954. case .year: return value == 1 ? "/ year" : "/ \(value) years"
  955. @unknown default: return ""
  956. }
  957. }
  958. private func setPurchasing(_ isPurchasing: Bool) {
  959. for button in planPurchaseButtons.values {
  960. button.isEnabled = !isPurchasing
  961. }
  962. }
  963. private func purchasePlan(planKey: String) async {
  964. setPurchasing(true)
  965. defer { setPurchasing(false) }
  966. do {
  967. let completed = try await subscriptionStore.purchase(planKey: planKey)
  968. guard completed else { return }
  969. AppRatingCoordinator.shared.scheduleReviewAfterSubscriptionPurchase()
  970. let alert = NSAlert()
  971. alert.messageText = "You're subscribed"
  972. alert.informativeText = "Thank you — Pro features are now available."
  973. alert.alertStyle = .informational
  974. alert.addButton(withTitle: "OK")
  975. if let window = view.window {
  976. alert.beginSheetModal(for: window) { [weak self] _ in
  977. self?.dismissPremiumSheetFromParentIfNeeded()
  978. }
  979. } else {
  980. alert.runModal()
  981. dismissPremiumSheetFromParentIfNeeded()
  982. }
  983. } catch {
  984. await MainActor.run {
  985. self.presentPurchaseError(error)
  986. }
  987. }
  988. }
  989. private func restorePurchases() async {
  990. setPurchasing(true)
  991. defer { setPurchasing(false) }
  992. do {
  993. try await subscriptionStore.restorePurchases()
  994. let active = subscriptionStore.isProActive
  995. let alert = NSAlert()
  996. if active {
  997. alert.messageText = "Purchases restored"
  998. alert.informativeText = "Your subscription is active."
  999. } else {
  1000. alert.messageText = "No subscription found"
  1001. alert.informativeText = "There was nothing to restore for this Apple ID."
  1002. }
  1003. alert.alertStyle = .informational
  1004. alert.addButton(withTitle: "OK")
  1005. if let window = view.window {
  1006. alert.beginSheetModal(for: window) { [weak self] _ in
  1007. if active {
  1008. self?.dismissPremiumSheetFromParentIfNeeded()
  1009. }
  1010. }
  1011. } else {
  1012. alert.runModal()
  1013. if active {
  1014. dismissPremiumSheetFromParentIfNeeded()
  1015. }
  1016. }
  1017. } catch {
  1018. await MainActor.run {
  1019. self.presentPurchaseError(error)
  1020. }
  1021. }
  1022. }
  1023. private func presentPurchaseError(_ error: Error) {
  1024. let alert = NSAlert()
  1025. alert.messageText = "Something went wrong"
  1026. if let localized = error as? LocalizedError {
  1027. var parts: [String] = []
  1028. if let description = localized.errorDescription {
  1029. parts.append(description)
  1030. }
  1031. if let recovery = localized.recoverySuggestion {
  1032. parts.append(recovery)
  1033. }
  1034. alert.informativeText = parts.isEmpty ? error.localizedDescription : parts.joined(separator: "\n\n")
  1035. } else {
  1036. alert.informativeText = error.localizedDescription
  1037. }
  1038. alert.alertStyle = .warning
  1039. alert.addButton(withTitle: "OK")
  1040. if let window = view.window {
  1041. alert.beginSheetModal(for: window)
  1042. } else {
  1043. alert.runModal()
  1044. }
  1045. }
  1046. private func dismissPremiumSheetFromParentIfNeeded() {
  1047. guard let sheet = view.window, let parent = sheet.sheetParent else { return }
  1048. parent.endSheet(sheet)
  1049. }
  1050. @objc private func didTapClose() {
  1051. guard let window = view.window else { return }
  1052. if let parent = window.sheetParent {
  1053. parent.endSheet(window)
  1054. return
  1055. }
  1056. window.close()
  1057. }
  1058. private func applyCurrentAppearance() {
  1059. view.window?.backgroundColor = PremiumPlansWindowController.paywallSheetBackground
  1060. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  1061. premiumTitleLabel?.textColor = Theme.primaryText
  1062. premiumSubtitleLabel?.textColor = Theme.secondaryText
  1063. for target in pricingCardTargets {
  1064. target.card.updateBorderColors(base: Theme.cardBorder, hover: Theme.accent)
  1065. target.card.layer?.backgroundColor = Theme.cardBackground.cgColor
  1066. target.iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1067. target.planIconView.contentTintColor = planIconTint(planId: target.planId)
  1068. target.titleLabel.textColor = Theme.primaryText
  1069. target.subtitleLabel.textColor = Theme.secondaryText
  1070. target.priceLabel.textColor = Theme.primaryText
  1071. target.periodLabel.textColor = Theme.secondaryText
  1072. target.billingLabel?.textColor = Theme.secondaryText
  1073. target.divider.borderColor = Theme.divider
  1074. for label in target.featureLabels {
  1075. label.textColor = Theme.primaryText
  1076. }
  1077. for icon in target.featureIcons {
  1078. icon.contentTintColor = Theme.iconTint
  1079. }
  1080. target.purchaseButton.refreshAppearance()
  1081. }
  1082. if let trustBadgesRow {
  1083. trustBadgesRow.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1084. trustBadgesRow.layer?.borderColor = Theme.divider.cgColor
  1085. for case let badge as NSStackView in trustBadgesRow.arrangedSubviews {
  1086. for case let image as NSImageView in badge.arrangedSubviews {
  1087. image.contentTintColor = Theme.primaryText
  1088. }
  1089. for case let textStack as NSStackView in badge.arrangedSubviews {
  1090. let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
  1091. if labels.count >= 2 {
  1092. labels[0].textColor = Theme.primaryText
  1093. labels[1].textColor = Theme.secondaryText
  1094. }
  1095. }
  1096. }
  1097. }
  1098. for button in footerLinkButtons {
  1099. button.contentTintColor = Theme.secondaryText
  1100. }
  1101. premiumCloseButton?.refreshAppearance(hovered: false)
  1102. }
  1103. private func planIconTint(planId: String) -> NSColor {
  1104. switch planId {
  1105. case "monthly": Theme.accent
  1106. case "yearly": Theme.successText
  1107. default: Theme.iconTint
  1108. }
  1109. }
  1110. }