Aucune description

PremiumPlansWindowController.swift 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  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 = L("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: L("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. let billedPillLabel: NSTextField?
  429. }
  430. private enum FeatureListMetrics {
  431. static let rowSpacing = CGFloat(8)
  432. static let iconLabelSpacing = CGFloat(8)
  433. static let edgeInsets = NSEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  434. /// Caps feature list height so pricing cards do not push the footer off-screen.
  435. static let maxScrollHeight = CGFloat(168)
  436. }
  437. private let subscriptionStore = SubscriptionStore.shared
  438. private var planPriceFields: [String: (price: NSTextField, period: NSTextField)] = [:]
  439. private var planPurchaseButtons: [String: NSButton] = [:]
  440. private var subscriptionPrimaryFooterButton: NSButton?
  441. private var premiumCloseButton: PremiumCloseHoverButton?
  442. private var subscriptionStatusObservation: NSObjectProtocol?
  443. private var appearanceObserver: NSObjectProtocol?
  444. private var languageObserver: NSObjectProtocol?
  445. /// Core Pro capabilities shown on every pricing card (replaces generic “All premium features”).
  446. private var proCapabilityFeatures: [String] {
  447. [
  448. L("Unlimited AI job search on Home"),
  449. L("Save jobs & open listings in-app"),
  450. L("CV Maker, profiles & PDF export"),
  451. L("Role, company & skill shortcuts")
  452. ]
  453. }
  454. private var plans: [Plan] {
  455. [
  456. Plan(
  457. id: "weekly",
  458. title: L("Weekly"),
  459. subtitle: L("Flexible and commitment-free"),
  460. period: L("/ week"),
  461. billedPill: "",
  462. billedLine: "",
  463. crossedPrice: nil,
  464. savingsText: nil,
  465. features: proCapabilityFeatures + [
  466. L("Perfect for short-term job hunts"),
  467. L("Cancel anytime")
  468. ],
  469. iconName: "paperplane.fill",
  470. iconTint: Theme.iconTint,
  471. highlight: false
  472. ),
  473. Plan(
  474. id: "monthly",
  475. title: L("Monthly"),
  476. subtitle: L("Balanced for regular productivity"),
  477. period: L("/ month"),
  478. billedPill: "",
  479. billedLine: "",
  480. crossedPrice: nil,
  481. savingsText: nil,
  482. features: proCapabilityFeatures + [
  483. L("Best for regular job seekers"),
  484. L("Priority support")
  485. ],
  486. iconName: "bolt.fill",
  487. iconTint: Theme.accent,
  488. highlight: true
  489. ),
  490. Plan(
  491. id: "yearly",
  492. title: L("Yearly"),
  493. subtitle: L("Best value for long-term users"),
  494. period: L("/ year"),
  495. billedPill: L("3 days free trial"),
  496. billedLine: "",
  497. crossedPrice: nil,
  498. savingsText: nil,
  499. features: proCapabilityFeatures + [
  500. L("Lowest effective monthly cost"),
  501. L("Ideal for long-term use")
  502. ],
  503. iconName: "crown.fill",
  504. iconTint: Theme.successText,
  505. highlight: false
  506. )
  507. ]
  508. }
  509. private let pageGradient = CAGradientLayer()
  510. private var premiumTitleLabel: NSTextField?
  511. private var premiumSubtitleLabel: NSTextField?
  512. private var pricingCardTargets: [PricingCardAppearanceTarget] = []
  513. private weak var trustBadgesRow: NSStackView?
  514. private var footerLinkButtons: [FooterLinkButton] = []
  515. deinit {
  516. if let subscriptionStatusObservation {
  517. NotificationCenter.default.removeObserver(subscriptionStatusObservation)
  518. }
  519. if let appearanceObserver {
  520. NotificationCenter.default.removeObserver(appearanceObserver)
  521. }
  522. if let languageObserver {
  523. NotificationCenter.default.removeObserver(languageObserver)
  524. }
  525. }
  526. override func viewDidLoad() {
  527. super.viewDidLoad()
  528. appearanceObserver = NotificationCenter.default.addObserver(
  529. forName: AppAppearanceManager.didChangeNotification,
  530. object: nil,
  531. queue: .main
  532. ) { [weak self] _ in
  533. self?.applyCurrentAppearance()
  534. }
  535. languageObserver = NotificationCenter.default.addObserver(
  536. forName: AppLanguageManager.didChangeNotification,
  537. object: nil,
  538. queue: .main
  539. ) { [weak self] _ in
  540. self?.applyLocalizedStrings()
  541. }
  542. subscriptionStatusObservation = NotificationCenter.default.addObserver(
  543. forName: .subscriptionStatusDidChange,
  544. object: nil,
  545. queue: .main
  546. ) { [weak self] _ in
  547. Task { @MainActor in
  548. await self?.subscriptionStore.loadProducts()
  549. self?.applyStorePricing()
  550. self?.updateSubscriptionPrimaryFooter()
  551. self?.updatePremiumCloseButtonVisibility()
  552. }
  553. }
  554. Task { @MainActor in
  555. await loadStoreProducts()
  556. }
  557. }
  558. override func viewDidLayout() {
  559. super.viewDidLayout()
  560. pageGradient.frame = view.bounds
  561. }
  562. override func loadView() {
  563. view = NSView()
  564. view.wantsLayer = true
  565. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  566. pageGradient.startPoint = CGPoint(x: 0, y: 1)
  567. pageGradient.endPoint = CGPoint(x: 1, y: 0)
  568. view.layer?.addSublayer(pageGradient)
  569. setupLayout()
  570. applyCurrentAppearance()
  571. }
  572. private func setupLayout() {
  573. let closeButton = PremiumCloseHoverButton(target: self, action: #selector(didTapClose))
  574. let crownIcon = NSImageView()
  575. crownIcon.translatesAutoresizingMaskIntoConstraints = false
  576. crownIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  577. crownIcon.image = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: nil)
  578. crownIcon.contentTintColor = NSColor(srgbRed: 254 / 255, green: 214 / 255, blue: 92 / 255, alpha: 1)
  579. let title = NSTextField(labelWithString: L("Upgrade to Pro"))
  580. title.font = .systemFont(ofSize: 40, weight: .semibold)
  581. title.textColor = Theme.primaryText
  582. title.alignment = .center
  583. premiumTitleLabel = title
  584. let subtitle = NSTextField(labelWithString: L("Unlock unlimited access to premium tools and boost your productivity."))
  585. subtitle.font = .systemFont(ofSize: 14, weight: .regular)
  586. subtitle.textColor = Theme.secondaryText
  587. subtitle.alignment = .center
  588. premiumSubtitleLabel = subtitle
  589. pricingCardTargets = []
  590. let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
  591. cardsRow.orientation = .horizontal
  592. cardsRow.spacing = 14
  593. cardsRow.alignment = .top
  594. cardsRow.distribution = .fillEqually
  595. cardsRow.translatesAutoresizingMaskIntoConstraints = false
  596. let trustRow = makeTrustRow()
  597. let footerRow = makeFooterRow()
  598. let headerStack = NSStackView(views: [crownIcon, title, subtitle])
  599. headerStack.orientation = .vertical
  600. headerStack.spacing = 10
  601. headerStack.alignment = .centerX
  602. headerStack.translatesAutoresizingMaskIntoConstraints = false
  603. let bodyStack = NSStackView(views: [cardsRow, trustRow])
  604. bodyStack.orientation = .vertical
  605. bodyStack.spacing = 16
  606. bodyStack.alignment = .centerX
  607. bodyStack.translatesAutoresizingMaskIntoConstraints = false
  608. let scrollView = NSScrollView()
  609. scrollView.hasVerticalScroller = true
  610. scrollView.autohidesScrollers = true
  611. scrollView.drawsBackground = false
  612. scrollView.borderType = .noBorder
  613. scrollView.translatesAutoresizingMaskIntoConstraints = false
  614. let scrollDocument = NSView()
  615. scrollDocument.translatesAutoresizingMaskIntoConstraints = false
  616. scrollView.documentView = scrollDocument
  617. scrollDocument.addSubview(bodyStack)
  618. view.addSubview(headerStack)
  619. view.addSubview(scrollView)
  620. view.addSubview(footerRow)
  621. view.addSubview(closeButton)
  622. let scrollClip = scrollView.contentView
  623. NSLayoutConstraint.activate([
  624. headerStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  625. headerStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  626. headerStack.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
  627. scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  628. scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  629. scrollView.topAnchor.constraint(equalTo: headerStack.bottomAnchor, constant: 12),
  630. scrollView.bottomAnchor.constraint(equalTo: footerRow.topAnchor, constant: -12),
  631. footerRow.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  632. footerRow.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  633. footerRow.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
  634. footerRow.heightAnchor.constraint(greaterThanOrEqualToConstant: 32),
  635. scrollDocument.leadingAnchor.constraint(equalTo: scrollClip.leadingAnchor),
  636. scrollDocument.trailingAnchor.constraint(equalTo: scrollClip.trailingAnchor),
  637. scrollDocument.topAnchor.constraint(equalTo: scrollClip.topAnchor),
  638. scrollDocument.widthAnchor.constraint(equalTo: scrollClip.widthAnchor),
  639. scrollDocument.bottomAnchor.constraint(equalTo: bodyStack.bottomAnchor, constant: 8),
  640. bodyStack.leadingAnchor.constraint(equalTo: scrollDocument.leadingAnchor),
  641. bodyStack.trailingAnchor.constraint(equalTo: scrollDocument.trailingAnchor),
  642. bodyStack.topAnchor.constraint(equalTo: scrollDocument.topAnchor, constant: 4),
  643. bodyStack.widthAnchor.constraint(equalTo: scrollDocument.widthAnchor),
  644. cardsRow.widthAnchor.constraint(equalTo: bodyStack.widthAnchor),
  645. trustRow.widthAnchor.constraint(equalTo: bodyStack.widthAnchor),
  646. closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  647. closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
  648. closeButton.widthAnchor.constraint(equalToConstant: 30),
  649. closeButton.heightAnchor.constraint(equalToConstant: 30),
  650. crownIcon.heightAnchor.constraint(equalToConstant: 20)
  651. ])
  652. premiumCloseButton = closeButton
  653. updatePremiumCloseButtonVisibility()
  654. }
  655. private func updatePremiumCloseButtonVisibility() {
  656. premiumCloseButton?.isHidden = !subscriptionStore.isProActive
  657. }
  658. private func makePricingCard(_ plan: Plan) -> NSView {
  659. let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
  660. card.translatesAutoresizingMaskIntoConstraints = false
  661. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  662. let iconWell = NSView()
  663. iconWell.translatesAutoresizingMaskIntoConstraints = false
  664. iconWell.wantsLayer = true
  665. iconWell.layer?.cornerRadius = 10
  666. iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  667. iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
  668. iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
  669. let icon = NSImageView()
  670. icon.translatesAutoresizingMaskIntoConstraints = false
  671. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  672. icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
  673. icon.contentTintColor = plan.iconTint
  674. iconWell.addSubview(icon)
  675. NSLayoutConstraint.activate([
  676. icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
  677. icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
  678. ])
  679. let titleLabel = NSTextField(labelWithString: plan.title)
  680. titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  681. titleLabel.textColor = Theme.primaryText
  682. titleLabel.alignment = .center
  683. let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
  684. subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
  685. subtitleLabel.textColor = Theme.secondaryText
  686. subtitleLabel.alignment = .center
  687. let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
  688. topRightTag.isHidden = plan.billedPill.isEmpty
  689. topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
  690. let priceLabel = NSTextField(labelWithString: Self.unloadedPricePlaceholder)
  691. priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
  692. priceLabel.textColor = Theme.primaryText
  693. let periodLabel = NSTextField(labelWithString: plan.period)
  694. periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
  695. periodLabel.textColor = Theme.secondaryText
  696. let priceRow = NSStackView(views: [priceLabel, periodLabel])
  697. priceRow.orientation = .horizontal
  698. priceRow.spacing = 4
  699. priceRow.alignment = .firstBaseline
  700. let billingLabel = NSTextField(labelWithString: plan.billedLine)
  701. billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
  702. billingLabel.textColor = Theme.secondaryText
  703. let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
  704. let divider = NSBox()
  705. divider.boxType = .separator
  706. divider.translatesAutoresizingMaskIntoConstraints = false
  707. divider.borderColor = Theme.divider
  708. let featureRows = plan.features.map(makeFeatureRow(_:))
  709. let featuresStack = NSStackView(views: featureRows)
  710. featuresStack.orientation = .vertical
  711. featuresStack.spacing = FeatureListMetrics.rowSpacing
  712. featuresStack.alignment = .leading
  713. featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
  714. featuresStack.setContentCompressionResistancePriority(.required, for: .vertical)
  715. featuresStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  716. for row in featureRows {
  717. row.setContentCompressionResistancePriority(.required, for: .vertical)
  718. }
  719. let featuresScroll = makeFeatureListScroll(featuresStack: featuresStack)
  720. let selectButton = PlanPurchaseHoverButton(
  721. planId: plan.id,
  722. title: String(format: L("Get %@"), plan.title),
  723. isPrimaryStyle: plan.highlight,
  724. target: self,
  725. action: #selector(didTapSelectPlan)
  726. )
  727. planPurchaseButtons[plan.id] = selectButton
  728. planPriceFields[plan.id] = (priceLabel, periodLabel)
  729. selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
  730. let featureLabels = featureRows.compactMap { row -> NSTextField? in
  731. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSTextField }.first
  732. }
  733. let featureIcons = featureRows.compactMap { row -> NSImageView? in
  734. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSImageView }.first
  735. }
  736. pricingCardTargets.append(
  737. PricingCardAppearanceTarget(
  738. card: card,
  739. iconWell: iconWell,
  740. planIconView: icon,
  741. planId: plan.id,
  742. titleLabel: titleLabel,
  743. subtitleLabel: subtitleLabel,
  744. priceLabel: priceLabel,
  745. periodLabel: periodLabel,
  746. billingLabel: plan.billedLine.isEmpty ? nil : billingLabel,
  747. divider: divider,
  748. featureLabels: featureLabels,
  749. featureIcons: featureIcons,
  750. purchaseButton: selectButton,
  751. billedPillLabel: plan.billedPill.isEmpty ? nil : topRightTag
  752. )
  753. )
  754. var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
  755. if !plan.billedLine.isEmpty {
  756. contentViews.append(billingLabel)
  757. }
  758. if plan.crossedPrice != nil, plan.savingsText != nil {
  759. contentViews.append(inlinePriceInfo)
  760. }
  761. contentViews.append(contentsOf: [divider, featuresScroll])
  762. let column = NSStackView(views: contentViews + [selectButton])
  763. column.orientation = .vertical
  764. column.spacing = 10
  765. column.alignment = .centerX
  766. column.distribution = .fill
  767. column.translatesAutoresizingMaskIntoConstraints = false
  768. card.addSubview(column)
  769. card.addSubview(topRightTag)
  770. NSLayoutConstraint.activate([
  771. divider.widthAnchor.constraint(equalTo: column.widthAnchor),
  772. featuresScroll.widthAnchor.constraint(equalTo: column.widthAnchor),
  773. column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  774. column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  775. column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  776. column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
  777. selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
  778. topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
  779. topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
  780. ])
  781. return card
  782. }
  783. private func makeFeatureListScroll(featuresStack: NSStackView) -> NSScrollView {
  784. let scroll = NSScrollView()
  785. scroll.hasVerticalScroller = true
  786. scroll.autohidesScrollers = true
  787. scroll.drawsBackground = false
  788. scroll.borderType = .noBorder
  789. scroll.translatesAutoresizingMaskIntoConstraints = false
  790. let document = NSView()
  791. document.translatesAutoresizingMaskIntoConstraints = false
  792. featuresStack.translatesAutoresizingMaskIntoConstraints = false
  793. scroll.documentView = document
  794. document.addSubview(featuresStack)
  795. NSLayoutConstraint.activate([
  796. scroll.heightAnchor.constraint(equalToConstant: FeatureListMetrics.maxScrollHeight),
  797. document.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  798. document.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  799. document.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  800. document.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
  801. document.bottomAnchor.constraint(equalTo: featuresStack.bottomAnchor, constant: FeatureListMetrics.edgeInsets.bottom),
  802. featuresStack.leadingAnchor.constraint(equalTo: document.leadingAnchor, constant: FeatureListMetrics.edgeInsets.left),
  803. featuresStack.trailingAnchor.constraint(equalTo: document.trailingAnchor, constant: -FeatureListMetrics.edgeInsets.right),
  804. featuresStack.topAnchor.constraint(equalTo: document.topAnchor, constant: FeatureListMetrics.edgeInsets.top),
  805. featuresStack.widthAnchor.constraint(equalTo: document.widthAnchor, constant: -(FeatureListMetrics.edgeInsets.left + FeatureListMetrics.edgeInsets.right))
  806. ])
  807. return scroll
  808. }
  809. private func makeFeatureRow(_ text: String) -> NSView {
  810. let icon = NSImageView()
  811. icon.translatesAutoresizingMaskIntoConstraints = false
  812. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  813. icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
  814. icon.contentTintColor = Theme.iconTint
  815. icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
  816. icon.heightAnchor.constraint(equalToConstant: 14).isActive = true
  817. icon.setContentHuggingPriority(.required, for: .horizontal)
  818. icon.setContentHuggingPriority(.required, for: .vertical)
  819. let label = NSTextField(wrappingLabelWithString: text)
  820. label.font = .systemFont(ofSize: 13, weight: .medium)
  821. label.textColor = Theme.primaryText
  822. label.alignment = .left
  823. label.lineBreakMode = .byWordWrapping
  824. label.maximumNumberOfLines = 0
  825. label.cell?.wraps = true
  826. label.cell?.isScrollable = false
  827. label.setContentCompressionResistancePriority(.required, for: .vertical)
  828. label.setContentHuggingPriority(.required, for: .vertical)
  829. label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  830. label.setContentHuggingPriority(.defaultLow, for: .horizontal)
  831. let row = NSStackView(views: [icon, label])
  832. row.orientation = .horizontal
  833. row.spacing = FeatureListMetrics.iconLabelSpacing
  834. row.alignment = .top
  835. row.distribution = .fill
  836. row.translatesAutoresizingMaskIntoConstraints = false
  837. return row
  838. }
  839. private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
  840. guard let oldPrice, let newPrice else {
  841. return NSTextField(labelWithString: "")
  842. }
  843. let full = NSMutableAttributedString()
  844. let oldAttributes: [NSAttributedString.Key: Any] = [
  845. .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
  846. .foregroundColor: Theme.secondaryText,
  847. .strikethroughStyle: NSUnderlineStyle.single.rawValue
  848. ]
  849. let newAttributes: [NSAttributedString.Key: Any] = [
  850. .font: NSFont.systemFont(ofSize: 12, weight: .bold),
  851. .foregroundColor: Theme.successText
  852. ]
  853. full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
  854. full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
  855. let label = NSTextField(labelWithAttributedString: full)
  856. return label
  857. }
  858. private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
  859. let pill = NSTextField(labelWithString: text)
  860. pill.font = .systemFont(ofSize: 10, weight: .semibold)
  861. pill.textColor = textColor
  862. pill.alignment = .center
  863. pill.wantsLayer = true
  864. pill.layer?.backgroundColor = tint.cgColor
  865. pill.layer?.cornerRadius = 9
  866. pill.translatesAutoresizingMaskIntoConstraints = false
  867. pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
  868. pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
  869. return pill
  870. }
  871. private func makeTrustRow() -> NSView {
  872. let badges = NSStackView(views: [
  873. trustBadge(icon: "shield.fill", title: L("Secure Payments"), subtitle: L("Your payment is 100% secure.")),
  874. trustBadge(icon: "arrow.counterclockwise", title: L("Cancel Anytime"), subtitle: L("No commitment, cancel anytime.")),
  875. trustBadge(icon: "headphones", title: L("24/7 Support"), subtitle: L("We're here to help you anytime.")),
  876. trustBadge(icon: "lock.fill", title: L("Privacy First"), subtitle: L("Your data is safe with us."))
  877. ])
  878. badges.orientation = .horizontal
  879. badges.alignment = .centerY
  880. badges.distribution = .fillEqually
  881. badges.spacing = 12
  882. badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
  883. badges.translatesAutoresizingMaskIntoConstraints = false
  884. badges.wantsLayer = true
  885. badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
  886. badges.layer?.borderColor = Theme.divider.cgColor
  887. badges.layer?.borderWidth = 1
  888. badges.layer?.cornerRadius = 10
  889. badges.setHuggingPriority(.defaultLow, for: .horizontal)
  890. badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
  891. trustBadgesRow = badges
  892. return badges
  893. }
  894. private func makeFooterRow() -> NSView {
  895. footerLinkButtons = []
  896. let primary = footerActionCell(
  897. title: subscriptionPrimaryFooterTitle(),
  898. action: #selector(didTapPrimaryFooterSubscriptionAction),
  899. showsTrailingDivider: true
  900. )
  901. subscriptionPrimaryFooterButton = primary.button
  902. let entries: [(text: String, action: Selector)] = [
  903. (L("Restore Purchase"), #selector(didTapRestorePurchases)),
  904. (L("Privacy Policy"), #selector(didTapFooterPrivacyPolicy)),
  905. (L("Terms of Use"), #selector(didTapFooterTermsOfServices)),
  906. (L("Support"), #selector(didTapFooterSupport))
  907. ]
  908. let cells = [primary.container] + entries.enumerated().map { index, entry in
  909. footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
  910. }
  911. let links = NSStackView(views: cells)
  912. links.orientation = .horizontal
  913. links.distribution = .fillEqually
  914. links.spacing = 0
  915. links.alignment = .centerY
  916. links.translatesAutoresizingMaskIntoConstraints = false
  917. return links
  918. }
  919. private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
  920. let container = NSView()
  921. container.translatesAutoresizingMaskIntoConstraints = false
  922. let button = FooterLinkButton(title: title, target: self, action: action)
  923. button.isBordered = false
  924. button.bezelStyle = .rounded
  925. button.font = .systemFont(ofSize: 12, weight: .medium)
  926. button.contentTintColor = Theme.secondaryText
  927. button.focusRingType = .none
  928. button.translatesAutoresizingMaskIntoConstraints = false
  929. footerLinkButtons.append(button)
  930. container.addSubview(button)
  931. var constraints: [NSLayoutConstraint] = [
  932. button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  933. button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  934. ]
  935. if showsTrailingDivider {
  936. let divider = footerDivider()
  937. container.addSubview(divider)
  938. constraints.append(contentsOf: [
  939. divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  940. divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  941. ])
  942. }
  943. NSLayoutConstraint.activate(constraints)
  944. return (container, button)
  945. }
  946. private enum PrimaryFooterSubscriptionTitle {
  947. static var manage: String { L("Manage Subscription") }
  948. static var continueFree: String { L("Continue with free plan") }
  949. }
  950. private func subscriptionPrimaryFooterTitle() -> String {
  951. subscriptionStore.isProActive ? PrimaryFooterSubscriptionTitle.manage : PrimaryFooterSubscriptionTitle.continueFree
  952. }
  953. private func updateSubscriptionPrimaryFooter() {
  954. subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
  955. }
  956. private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
  957. let image = NSImageView()
  958. image.translatesAutoresizingMaskIntoConstraints = false
  959. image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  960. image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
  961. image.contentTintColor = Theme.primaryText
  962. let titleLabel = NSTextField(labelWithString: title)
  963. titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
  964. titleLabel.textColor = Theme.primaryText
  965. let subtitleLabel = NSTextField(labelWithString: subtitle)
  966. subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
  967. subtitleLabel.textColor = Theme.secondaryText
  968. let textStack = NSStackView(views: [titleLabel, subtitleLabel])
  969. textStack.orientation = .vertical
  970. textStack.spacing = 2
  971. textStack.alignment = .leading
  972. let stack = NSStackView(views: [image, textStack])
  973. stack.orientation = .horizontal
  974. stack.spacing = 8
  975. stack.alignment = .leading
  976. stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  977. stack.wantsLayer = true
  978. stack.layer?.backgroundColor = NSColor.clear.cgColor
  979. return stack
  980. }
  981. private func footerDivider() -> NSBox {
  982. let divider = NSBox()
  983. divider.boxType = .separator
  984. divider.borderColor = Theme.divider
  985. divider.translatesAutoresizingMaskIntoConstraints = false
  986. divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
  987. divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
  988. return divider
  989. }
  990. @objc private func didTapSelectPlan(_ sender: NSButton) {
  991. guard let planKey = sender.identifier?.rawValue else { return }
  992. Task { await purchasePlan(planKey: planKey) }
  993. }
  994. @objc private func didTapPrimaryFooterSubscriptionAction(_ sender: NSButton) {
  995. let userTappedManage = (sender.title == PrimaryFooterSubscriptionTitle.manage)
  996. Task { @MainActor [weak self] in
  997. guard let self else { return }
  998. await subscriptionStore.refreshEntitlements(deep: true)
  999. updateSubscriptionPrimaryFooter()
  1000. let active = subscriptionStore.isProActive
  1001. if active || userTappedManage {
  1002. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
  1003. NSWorkspace.shared.open(url)
  1004. return
  1005. }
  1006. // Non-pro: dismiss paywall and return to the home (dashboard) window.
  1007. dismissPremiumSheetFromParentIfNeeded()
  1008. }
  1009. }
  1010. @objc private func didTapRestorePurchases() {
  1011. Task { await restorePurchases() }
  1012. }
  1013. @objc private func didTapFooterPrivacyPolicy() {
  1014. AppLegalURLs.openInSafari(AppLegalURLs.privacyPolicy)
  1015. }
  1016. @objc private func didTapFooterTermsOfServices() {
  1017. AppLegalURLs.openInSafari(AppLegalURLs.termsOfUse)
  1018. }
  1019. @objc private func didTapFooterSupport() {
  1020. AppLegalURLs.openInSafari(AppLegalURLs.support)
  1021. }
  1022. private func loadStoreProducts() async {
  1023. await subscriptionStore.refreshEntitlements(deep: true)
  1024. await subscriptionStore.loadProducts()
  1025. applyStorePricing()
  1026. updateSubscriptionPrimaryFooter()
  1027. updatePremiumCloseButtonVisibility()
  1028. }
  1029. private func applyStorePricing() {
  1030. for plan in plans {
  1031. guard let fields = planPriceFields[plan.id] else { continue }
  1032. guard let product = subscriptionStore.product(forPlanKey: plan.id) else {
  1033. fields.price.stringValue = Self.unloadedPricePlaceholder
  1034. continue
  1035. }
  1036. fields.price.stringValue = product.displayPrice
  1037. if let period = product.subscription?.subscriptionPeriod {
  1038. fields.period.stringValue = periodSuffix(for: period)
  1039. }
  1040. }
  1041. }
  1042. private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
  1043. let value = period.value
  1044. switch period.unit {
  1045. case .day: return value == 1 ? L("/ day") : String(format: L("/ %d days"), value)
  1046. case .week: return value == 1 ? L("/ week") : String(format: L("/ %d weeks"), value)
  1047. case .month: return value == 1 ? L("/ month") : String(format: L("/ %d months"), value)
  1048. case .year: return value == 1 ? L("/ year") : String(format: L("/ %d years"), value)
  1049. @unknown default: return ""
  1050. }
  1051. }
  1052. private func setPurchasing(_ isPurchasing: Bool) {
  1053. for button in planPurchaseButtons.values {
  1054. button.isEnabled = !isPurchasing
  1055. }
  1056. }
  1057. private func purchasePlan(planKey: String) async {
  1058. setPurchasing(true)
  1059. defer { setPurchasing(false) }
  1060. do {
  1061. let completed = try await subscriptionStore.purchase(planKey: planKey)
  1062. guard completed else { return }
  1063. AppRatingCoordinator.shared.scheduleReviewAfterSubscriptionPurchase()
  1064. let alert = NSAlert()
  1065. alert.messageText = L("You're subscribed")
  1066. alert.informativeText = L("Thank you — Pro features are now available.")
  1067. alert.alertStyle = .informational
  1068. alert.addButton(withTitle: L("OK"))
  1069. if let window = view.window {
  1070. alert.beginSheetModal(for: window) { [weak self] _ in
  1071. self?.dismissPremiumSheetFromParentIfNeeded()
  1072. }
  1073. } else {
  1074. alert.runModal()
  1075. dismissPremiumSheetFromParentIfNeeded()
  1076. }
  1077. } catch {
  1078. await MainActor.run {
  1079. self.presentPurchaseError(error)
  1080. }
  1081. }
  1082. }
  1083. private func restorePurchases() async {
  1084. setPurchasing(true)
  1085. defer { setPurchasing(false) }
  1086. do {
  1087. try await subscriptionStore.restorePurchases()
  1088. let active = subscriptionStore.isProActive
  1089. let alert = NSAlert()
  1090. if active {
  1091. alert.messageText = L("Purchases restored")
  1092. alert.informativeText = L("Your subscription is active.")
  1093. } else {
  1094. alert.messageText = L("No subscription found")
  1095. alert.informativeText = L("There was nothing to restore for this Apple ID.")
  1096. }
  1097. alert.alertStyle = .informational
  1098. alert.addButton(withTitle: L("OK"))
  1099. if let window = view.window {
  1100. alert.beginSheetModal(for: window) { [weak self] _ in
  1101. if active {
  1102. self?.dismissPremiumSheetFromParentIfNeeded()
  1103. }
  1104. }
  1105. } else {
  1106. alert.runModal()
  1107. if active {
  1108. dismissPremiumSheetFromParentIfNeeded()
  1109. }
  1110. }
  1111. } catch {
  1112. await MainActor.run {
  1113. self.presentPurchaseError(error)
  1114. }
  1115. }
  1116. }
  1117. private func presentPurchaseError(_ error: Error) {
  1118. let alert = NSAlert()
  1119. alert.messageText = L("Something went wrong")
  1120. if let localized = error as? LocalizedError {
  1121. var parts: [String] = []
  1122. if let description = localized.errorDescription {
  1123. parts.append(description)
  1124. }
  1125. if let recovery = localized.recoverySuggestion {
  1126. parts.append(recovery)
  1127. }
  1128. alert.informativeText = parts.isEmpty ? error.localizedDescription : parts.joined(separator: "\n\n")
  1129. } else {
  1130. alert.informativeText = error.localizedDescription
  1131. }
  1132. alert.alertStyle = .warning
  1133. alert.addButton(withTitle: L("OK"))
  1134. if let window = view.window {
  1135. alert.beginSheetModal(for: window)
  1136. } else {
  1137. alert.runModal()
  1138. }
  1139. }
  1140. private func applyLocalizedStrings() {
  1141. view.window?.title = L("Premium Plans")
  1142. premiumTitleLabel?.stringValue = L("Upgrade to Pro")
  1143. premiumSubtitleLabel?.stringValue = L("Unlock unlimited access to premium tools and boost your productivity.")
  1144. for target in pricingCardTargets {
  1145. guard let plan = plans.first(where: { $0.id == target.planId }) else { continue }
  1146. target.titleLabel.stringValue = plan.title
  1147. target.subtitleLabel.stringValue = plan.subtitle
  1148. if subscriptionStore.product(forPlanKey: plan.id) == nil {
  1149. target.periodLabel.stringValue = plan.period
  1150. }
  1151. target.billedPillLabel?.stringValue = plan.billedPill
  1152. target.billedPillLabel?.isHidden = plan.billedPill.isEmpty
  1153. for (index, label) in target.featureLabels.enumerated() where index < plan.features.count {
  1154. label.stringValue = plan.features[index]
  1155. }
  1156. target.purchaseButton.title = String(format: L("Get %@"), plan.title)
  1157. }
  1158. if let trustBadgesRow {
  1159. let trustData: [(String, String)] = [
  1160. (L("Secure Payments"), L("Your payment is 100% secure.")),
  1161. (L("Cancel Anytime"), L("No commitment, cancel anytime.")),
  1162. (L("24/7 Support"), L("We're here to help you anytime.")),
  1163. (L("Privacy First"), L("Your data is safe with us."))
  1164. ]
  1165. for (index, subview) in trustBadgesRow.arrangedSubviews.enumerated() {
  1166. guard let badge = subview as? NSStackView, index < trustData.count else { continue }
  1167. for case let textStack as NSStackView in badge.arrangedSubviews {
  1168. let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
  1169. if labels.count >= 2 {
  1170. labels[0].stringValue = trustData[index].0
  1171. labels[1].stringValue = trustData[index].1
  1172. }
  1173. }
  1174. }
  1175. }
  1176. let footerTitles = [
  1177. subscriptionPrimaryFooterTitle(),
  1178. L("Restore Purchase"),
  1179. L("Privacy Policy"),
  1180. L("Terms of Use"),
  1181. L("Support")
  1182. ]
  1183. for (index, button) in footerLinkButtons.enumerated() where index < footerTitles.count {
  1184. button.title = footerTitles[index]
  1185. }
  1186. updateSubscriptionPrimaryFooter()
  1187. applyStorePricing()
  1188. }
  1189. private func dismissPremiumSheetFromParentIfNeeded() {
  1190. guard let sheet = view.window, let parent = sheet.sheetParent else { return }
  1191. parent.endSheet(sheet)
  1192. }
  1193. @objc private func didTapClose() {
  1194. guard let window = view.window else { return }
  1195. if let parent = window.sheetParent {
  1196. parent.endSheet(window)
  1197. return
  1198. }
  1199. window.close()
  1200. }
  1201. private func applyCurrentAppearance() {
  1202. view.window?.backgroundColor = PremiumPlansWindowController.paywallSheetBackground
  1203. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  1204. premiumTitleLabel?.textColor = Theme.primaryText
  1205. premiumSubtitleLabel?.textColor = Theme.secondaryText
  1206. for target in pricingCardTargets {
  1207. target.card.updateBorderColors(base: Theme.cardBorder, hover: Theme.accent)
  1208. target.card.layer?.backgroundColor = Theme.cardBackground.cgColor
  1209. target.iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1210. target.planIconView.contentTintColor = planIconTint(planId: target.planId)
  1211. target.titleLabel.textColor = Theme.primaryText
  1212. target.subtitleLabel.textColor = Theme.secondaryText
  1213. target.priceLabel.textColor = Theme.primaryText
  1214. target.periodLabel.textColor = Theme.secondaryText
  1215. target.billingLabel?.textColor = Theme.secondaryText
  1216. target.divider.borderColor = Theme.divider
  1217. for label in target.featureLabels {
  1218. label.textColor = Theme.primaryText
  1219. }
  1220. for icon in target.featureIcons {
  1221. icon.contentTintColor = Theme.iconTint
  1222. }
  1223. target.purchaseButton.refreshAppearance()
  1224. }
  1225. if let trustBadgesRow {
  1226. trustBadgesRow.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1227. trustBadgesRow.layer?.borderColor = Theme.divider.cgColor
  1228. for case let badge as NSStackView in trustBadgesRow.arrangedSubviews {
  1229. for case let image as NSImageView in badge.arrangedSubviews {
  1230. image.contentTintColor = Theme.primaryText
  1231. }
  1232. for case let textStack as NSStackView in badge.arrangedSubviews {
  1233. let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
  1234. if labels.count >= 2 {
  1235. labels[0].textColor = Theme.primaryText
  1236. labels[1].textColor = Theme.secondaryText
  1237. }
  1238. }
  1239. }
  1240. }
  1241. for button in footerLinkButtons {
  1242. button.contentTintColor = Theme.secondaryText
  1243. }
  1244. premiumCloseButton?.refreshAppearance(hovered: false)
  1245. }
  1246. private func planIconTint(planId: String) -> NSColor {
  1247. switch planId {
  1248. case "monthly": Theme.accent
  1249. case "yearly": Theme.successText
  1250. default: Theme.iconTint
  1251. }
  1252. }
  1253. }