PremiumPlansWindowController.swift 61 KB

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