PremiumPlansWindowController.swift 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  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. title.lineBreakMode = .byTruncatingTail
  607. title.maximumNumberOfLines = 1
  608. premiumTitleLabel = title
  609. let subtitle = NSTextField(labelWithString: L("Unlock unlimited access to premium tools and boost your productivity."))
  610. subtitle.font = .systemFont(ofSize: 14, weight: .regular)
  611. subtitle.textColor = Theme.secondaryText
  612. subtitle.alignment = .center
  613. subtitle.lineBreakMode = .byWordWrapping
  614. subtitle.maximumNumberOfLines = 2
  615. premiumSubtitleLabel = subtitle
  616. pricingCardTargets = []
  617. let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
  618. cardsRow.orientation = .horizontal
  619. cardsRow.spacing = 14
  620. cardsRow.alignment = .top
  621. cardsRow.distribution = .fillEqually
  622. cardsRow.translatesAutoresizingMaskIntoConstraints = false
  623. let trustRow = makeTrustRow()
  624. let footerRow = makeFooterRow()
  625. let headerStack = NSStackView(views: [crownIcon, title, subtitle])
  626. headerStack.orientation = .vertical
  627. headerStack.spacing = 10
  628. headerStack.alignment = .centerX
  629. headerStack.translatesAutoresizingMaskIntoConstraints = false
  630. headerStack.setContentHuggingPriority(.required, for: .vertical)
  631. headerStack.setContentCompressionResistancePriority(.required, for: .vertical)
  632. let paywallStack = NSStackView(views: [headerStack, cardsRow])
  633. paywallStack.orientation = .vertical
  634. paywallStack.spacing = 16
  635. paywallStack.setCustomSpacing(12, after: headerStack)
  636. paywallStack.alignment = .centerX
  637. paywallStack.translatesAutoresizingMaskIntoConstraints = false
  638. paywallStack.setContentHuggingPriority(.required, for: .vertical)
  639. paywallStack.setContentCompressionResistancePriority(.required, for: .vertical)
  640. let topFlex = NSView()
  641. topFlex.translatesAutoresizingMaskIntoConstraints = false
  642. topFlex.setContentHuggingPriority(.defaultLow, for: .vertical)
  643. topFlex.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  644. let bottomFlex = NSView()
  645. bottomFlex.translatesAutoresizingMaskIntoConstraints = false
  646. bottomFlex.setContentHuggingPriority(.defaultLow, for: .vertical)
  647. bottomFlex.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  648. let centeredColumn = NSStackView(views: [topFlex, paywallStack, bottomFlex])
  649. centeredColumn.orientation = .vertical
  650. centeredColumn.spacing = 0
  651. centeredColumn.translatesAutoresizingMaskIntoConstraints = false
  652. let scrollView = NSScrollView()
  653. scrollView.hasVerticalScroller = true
  654. scrollView.autohidesScrollers = true
  655. scrollView.drawsBackground = false
  656. scrollView.borderType = .noBorder
  657. scrollView.translatesAutoresizingMaskIntoConstraints = false
  658. let scrollDocument = NSView()
  659. scrollDocument.translatesAutoresizingMaskIntoConstraints = false
  660. scrollView.documentView = scrollDocument
  661. scrollDocument.addSubview(centeredColumn)
  662. view.addSubview(scrollView)
  663. view.addSubview(trustRow)
  664. view.addSubview(footerRow)
  665. view.addSubview(closeButton)
  666. let scrollClip = scrollView.contentView
  667. NSLayoutConstraint.activate([
  668. scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  669. scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  670. scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
  671. scrollView.bottomAnchor.constraint(equalTo: trustRow.topAnchor, constant: -16),
  672. trustRow.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  673. trustRow.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  674. trustRow.bottomAnchor.constraint(equalTo: footerRow.topAnchor, constant: -12),
  675. trustRow.heightAnchor.constraint(equalToConstant: 72),
  676. footerRow.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
  677. footerRow.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
  678. footerRow.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
  679. footerRow.heightAnchor.constraint(greaterThanOrEqualToConstant: 32),
  680. scrollDocument.leadingAnchor.constraint(equalTo: scrollClip.leadingAnchor),
  681. scrollDocument.trailingAnchor.constraint(equalTo: scrollClip.trailingAnchor),
  682. scrollDocument.topAnchor.constraint(equalTo: scrollClip.topAnchor),
  683. scrollDocument.widthAnchor.constraint(equalTo: scrollClip.widthAnchor),
  684. scrollDocument.bottomAnchor.constraint(equalTo: centeredColumn.bottomAnchor),
  685. scrollDocument.heightAnchor.constraint(greaterThanOrEqualTo: scrollClip.heightAnchor),
  686. centeredColumn.leadingAnchor.constraint(equalTo: scrollDocument.leadingAnchor),
  687. centeredColumn.trailingAnchor.constraint(equalTo: scrollDocument.trailingAnchor),
  688. centeredColumn.topAnchor.constraint(equalTo: scrollDocument.topAnchor),
  689. centeredColumn.bottomAnchor.constraint(equalTo: scrollDocument.bottomAnchor),
  690. centeredColumn.widthAnchor.constraint(equalTo: scrollDocument.widthAnchor),
  691. topFlex.heightAnchor.constraint(equalTo: bottomFlex.heightAnchor),
  692. paywallStack.widthAnchor.constraint(equalTo: centeredColumn.widthAnchor),
  693. headerStack.widthAnchor.constraint(equalTo: paywallStack.widthAnchor),
  694. title.widthAnchor.constraint(equalTo: headerStack.widthAnchor),
  695. subtitle.widthAnchor.constraint(equalTo: headerStack.widthAnchor),
  696. cardsRow.widthAnchor.constraint(equalTo: paywallStack.widthAnchor),
  697. closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  698. closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
  699. closeButton.widthAnchor.constraint(equalToConstant: 30),
  700. closeButton.heightAnchor.constraint(equalToConstant: 30),
  701. crownIcon.heightAnchor.constraint(equalToConstant: 20)
  702. ])
  703. premiumCloseButton = closeButton
  704. updatePremiumCloseButtonVisibility()
  705. applyLayoutDirection()
  706. }
  707. private func updatePremiumCloseButtonVisibility() {
  708. premiumCloseButton?.isHidden = !subscriptionStore.isProActive
  709. }
  710. private func makePricingCard(_ plan: Plan) -> NSView {
  711. let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
  712. card.translatesAutoresizingMaskIntoConstraints = false
  713. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  714. let iconWell = NSView()
  715. iconWell.translatesAutoresizingMaskIntoConstraints = false
  716. iconWell.wantsLayer = true
  717. iconWell.layer?.cornerRadius = 10
  718. iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  719. iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
  720. iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
  721. let icon = NSImageView()
  722. icon.translatesAutoresizingMaskIntoConstraints = false
  723. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  724. icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
  725. icon.contentTintColor = plan.iconTint
  726. iconWell.addSubview(icon)
  727. NSLayoutConstraint.activate([
  728. icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
  729. icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
  730. ])
  731. let titleLabel = NSTextField(labelWithString: plan.title)
  732. titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  733. titleLabel.textColor = Theme.primaryText
  734. titleLabel.alignment = .center
  735. let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
  736. subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
  737. subtitleLabel.textColor = Theme.secondaryText
  738. subtitleLabel.alignment = .center
  739. let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
  740. topRightTag.isHidden = plan.billedPill.isEmpty
  741. topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
  742. let priceLabel = NSTextField(labelWithString: Self.unloadedPricePlaceholder)
  743. priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
  744. priceLabel.textColor = Theme.primaryText
  745. let periodLabel = NSTextField(labelWithString: plan.period)
  746. periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
  747. periodLabel.textColor = Theme.secondaryText
  748. let priceRow = NSStackView(views: [priceLabel, periodLabel])
  749. priceRow.orientation = .horizontal
  750. priceRow.spacing = 4
  751. priceRow.alignment = .firstBaseline
  752. let billingLabel = NSTextField(labelWithString: plan.billedLine)
  753. billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
  754. billingLabel.textColor = Theme.secondaryText
  755. let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
  756. let divider = NSBox()
  757. divider.boxType = .separator
  758. divider.translatesAutoresizingMaskIntoConstraints = false
  759. divider.borderColor = Theme.divider
  760. let featureRows = plan.features.map(makeFeatureRow(_:))
  761. let featuresStack = NSStackView(views: featureRows)
  762. featuresStack.orientation = .vertical
  763. featuresStack.spacing = FeatureListMetrics.rowSpacing
  764. featuresStack.alignment = .width
  765. featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
  766. featuresStack.setContentCompressionResistancePriority(.required, for: .vertical)
  767. featuresStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  768. for row in featureRows {
  769. row.setContentCompressionResistancePriority(.required, for: .vertical)
  770. row.widthAnchor.constraint(equalTo: featuresStack.widthAnchor).isActive = true
  771. }
  772. let featuresScroll = makeFeatureListScroll(featuresStack: featuresStack)
  773. let selectButton = PlanPurchaseHoverButton(
  774. planId: plan.id,
  775. title: String(format: L("Get %@"), plan.title),
  776. isPrimaryStyle: plan.highlight,
  777. target: self,
  778. action: #selector(didTapSelectPlan)
  779. )
  780. planPurchaseButtons[plan.id] = selectButton
  781. planPriceFields[plan.id] = (priceLabel, periodLabel)
  782. selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
  783. let featureLabels = featureRows.compactMap { row -> NSTextField? in
  784. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSTextField }.first
  785. }
  786. let featureIcons = featureRows.compactMap { row -> NSImageView? in
  787. (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSImageView }.first
  788. }
  789. pricingCardTargets.append(
  790. PricingCardAppearanceTarget(
  791. card: card,
  792. iconWell: iconWell,
  793. planIconView: icon,
  794. planId: plan.id,
  795. titleLabel: titleLabel,
  796. subtitleLabel: subtitleLabel,
  797. priceLabel: priceLabel,
  798. periodLabel: periodLabel,
  799. billingLabel: plan.billedLine.isEmpty ? nil : billingLabel,
  800. divider: divider,
  801. featuresStack: featuresStack,
  802. featureLabels: featureLabels,
  803. featureIcons: featureIcons,
  804. purchaseButton: selectButton,
  805. billedPillLabel: plan.billedPill.isEmpty ? nil : topRightTag
  806. )
  807. )
  808. var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
  809. if !plan.billedLine.isEmpty {
  810. contentViews.append(billingLabel)
  811. }
  812. if plan.crossedPrice != nil, plan.savingsText != nil {
  813. contentViews.append(inlinePriceInfo)
  814. }
  815. contentViews.append(contentsOf: [divider, featuresScroll])
  816. let column = NSStackView(views: contentViews + [selectButton])
  817. column.orientation = .vertical
  818. column.spacing = 10
  819. column.alignment = .centerX
  820. column.distribution = .fill
  821. column.translatesAutoresizingMaskIntoConstraints = false
  822. card.addSubview(column)
  823. card.addSubview(topRightTag)
  824. NSLayoutConstraint.activate([
  825. divider.widthAnchor.constraint(equalTo: column.widthAnchor),
  826. featuresScroll.widthAnchor.constraint(equalTo: column.widthAnchor),
  827. column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  828. column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  829. column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  830. column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
  831. selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
  832. topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
  833. topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
  834. ])
  835. return card
  836. }
  837. private func makeFeatureListScroll(featuresStack: NSStackView) -> NSScrollView {
  838. let scroll = NSScrollView()
  839. scroll.hasVerticalScroller = true
  840. scroll.autohidesScrollers = true
  841. scroll.drawsBackground = false
  842. scroll.borderType = .noBorder
  843. scroll.translatesAutoresizingMaskIntoConstraints = false
  844. let document = NSView()
  845. document.translatesAutoresizingMaskIntoConstraints = false
  846. featuresStack.translatesAutoresizingMaskIntoConstraints = false
  847. scroll.documentView = document
  848. document.addSubview(featuresStack)
  849. NSLayoutConstraint.activate([
  850. scroll.heightAnchor.constraint(equalToConstant: FeatureListMetrics.maxScrollHeight),
  851. document.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  852. document.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  853. document.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  854. document.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
  855. document.bottomAnchor.constraint(equalTo: featuresStack.bottomAnchor, constant: FeatureListMetrics.edgeInsets.bottom),
  856. featuresStack.leadingAnchor.constraint(equalTo: document.leadingAnchor, constant: FeatureListMetrics.edgeInsets.left),
  857. featuresStack.trailingAnchor.constraint(equalTo: document.trailingAnchor, constant: -FeatureListMetrics.edgeInsets.right),
  858. featuresStack.topAnchor.constraint(equalTo: document.topAnchor, constant: FeatureListMetrics.edgeInsets.top),
  859. featuresStack.widthAnchor.constraint(equalTo: document.widthAnchor, constant: -(FeatureListMetrics.edgeInsets.left + FeatureListMetrics.edgeInsets.right))
  860. ])
  861. return scroll
  862. }
  863. private func makeFeatureRow(_ text: String) -> NSView {
  864. let icon = NSImageView()
  865. icon.translatesAutoresizingMaskIntoConstraints = false
  866. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
  867. icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
  868. icon.contentTintColor = Theme.iconTint
  869. icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
  870. icon.heightAnchor.constraint(equalToConstant: 14).isActive = true
  871. icon.setContentHuggingPriority(.required, for: .horizontal)
  872. icon.setContentHuggingPriority(.required, for: .vertical)
  873. let label = NSTextField(wrappingLabelWithString: text)
  874. label.font = .systemFont(ofSize: 13, weight: .medium)
  875. label.textColor = Theme.primaryText
  876. label.lineBreakMode = .byWordWrapping
  877. label.maximumNumberOfLines = 0
  878. label.cell?.wraps = true
  879. label.cell?.isScrollable = false
  880. label.attributedStringValue = AppLayoutDirection.attributedString(
  881. text,
  882. font: label.font ?? .systemFont(ofSize: 13, weight: .medium),
  883. color: Theme.primaryText
  884. )
  885. AppLayoutDirection.configureTextField(label)
  886. label.setContentCompressionResistancePriority(.required, for: .vertical)
  887. label.setContentHuggingPriority(.required, for: .vertical)
  888. label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  889. label.setContentHuggingPriority(.defaultLow, for: .horizontal)
  890. let row = NSStackView(views: [icon, label])
  891. row.orientation = .horizontal
  892. row.spacing = FeatureListMetrics.iconLabelSpacing
  893. row.alignment = .top
  894. row.distribution = .fill
  895. row.translatesAutoresizingMaskIntoConstraints = false
  896. row.userInterfaceLayoutDirection = AppLayoutDirection.interface
  897. return row
  898. }
  899. private func applyLayoutDirection() {
  900. let direction = AppLayoutDirection.interface
  901. view.userInterfaceLayoutDirection = direction
  902. for target in pricingCardTargets {
  903. target.card.userInterfaceLayoutDirection = direction
  904. target.featuresStack.userInterfaceLayoutDirection = direction
  905. target.featuresStack.alignment = .width
  906. if let scroll = target.featuresStack.enclosingFeatureListScrollView() {
  907. scroll.userInterfaceLayoutDirection = direction
  908. scroll.documentView?.userInterfaceLayoutDirection = direction
  909. }
  910. guard let plan = plans.first(where: { $0.id == target.planId }) else { continue }
  911. for (index, label) in target.featureLabels.enumerated() where index < plan.features.count {
  912. let font = label.font ?? .systemFont(ofSize: 13, weight: .medium)
  913. let color = label.textColor ?? Theme.primaryText
  914. label.attributedStringValue = AppLayoutDirection.attributedString(
  915. plan.features[index],
  916. font: font,
  917. color: color
  918. )
  919. AppLayoutDirection.configureTextField(label)
  920. }
  921. for row in target.featuresStack.arrangedSubviews {
  922. row.userInterfaceLayoutDirection = direction
  923. }
  924. }
  925. }
  926. private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
  927. guard let oldPrice, let newPrice else {
  928. return NSTextField(labelWithString: "")
  929. }
  930. let full = NSMutableAttributedString()
  931. let oldAttributes: [NSAttributedString.Key: Any] = [
  932. .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
  933. .foregroundColor: Theme.secondaryText,
  934. .strikethroughStyle: NSUnderlineStyle.single.rawValue
  935. ]
  936. let newAttributes: [NSAttributedString.Key: Any] = [
  937. .font: NSFont.systemFont(ofSize: 12, weight: .bold),
  938. .foregroundColor: Theme.successText
  939. ]
  940. full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
  941. full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
  942. let label = NSTextField(labelWithAttributedString: full)
  943. return label
  944. }
  945. private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
  946. let pill = NSTextField(labelWithString: text)
  947. pill.font = .systemFont(ofSize: 10, weight: .semibold)
  948. pill.textColor = textColor
  949. pill.alignment = .center
  950. pill.wantsLayer = true
  951. pill.layer?.backgroundColor = tint.cgColor
  952. pill.layer?.cornerRadius = 9
  953. pill.translatesAutoresizingMaskIntoConstraints = false
  954. pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
  955. pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
  956. return pill
  957. }
  958. private func makeTrustRow() -> NSView {
  959. let badges = NSStackView(views: [
  960. trustBadge(icon: "shield.fill", title: L("Secure Payments"), subtitle: L("Your payment is 100% secure.")),
  961. trustBadge(icon: "arrow.counterclockwise", title: L("Cancel Anytime"), subtitle: L("No commitment, cancel anytime.")),
  962. trustBadge(icon: "headphones", title: L("24/7 Support"), subtitle: L("We're here to help you anytime.")),
  963. trustBadge(icon: "lock.fill", title: L("Privacy First"), subtitle: L("Your data is safe with us."))
  964. ])
  965. badges.orientation = .horizontal
  966. badges.alignment = .centerY
  967. badges.distribution = .fillEqually
  968. badges.spacing = 12
  969. badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
  970. badges.translatesAutoresizingMaskIntoConstraints = false
  971. badges.wantsLayer = true
  972. badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
  973. badges.layer?.borderColor = Theme.divider.cgColor
  974. badges.layer?.borderWidth = 1
  975. badges.layer?.cornerRadius = 10
  976. badges.setHuggingPriority(.defaultLow, for: .horizontal)
  977. badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
  978. trustBadgesRow = badges
  979. return badges
  980. }
  981. private func makeFooterRow() -> NSView {
  982. footerLinkButtons = []
  983. let primary = footerActionCell(
  984. title: subscriptionPrimaryFooterTitle(),
  985. action: #selector(didTapPrimaryFooterSubscriptionAction),
  986. showsTrailingDivider: true
  987. )
  988. subscriptionPrimaryFooterButton = primary.button
  989. let entries: [(text: String, action: Selector)] = [
  990. (L("Restore Purchase"), #selector(didTapRestorePurchases)),
  991. (L("Privacy Policy"), #selector(didTapFooterPrivacyPolicy)),
  992. (L("Terms of Use"), #selector(didTapFooterTermsOfServices)),
  993. (L("Support"), #selector(didTapFooterSupport))
  994. ]
  995. let cells = [primary.container] + entries.enumerated().map { index, entry in
  996. footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
  997. }
  998. let links = NSStackView(views: cells)
  999. links.orientation = .horizontal
  1000. links.distribution = .fillEqually
  1001. links.spacing = 0
  1002. links.alignment = .centerY
  1003. links.translatesAutoresizingMaskIntoConstraints = false
  1004. return links
  1005. }
  1006. private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
  1007. let container = NSView()
  1008. container.translatesAutoresizingMaskIntoConstraints = false
  1009. let button = FooterLinkButton(title: title, target: self, action: action)
  1010. button.isBordered = false
  1011. button.bezelStyle = .rounded
  1012. button.font = .systemFont(ofSize: 12, weight: .medium)
  1013. button.contentTintColor = Theme.secondaryText
  1014. button.focusRingType = .none
  1015. button.translatesAutoresizingMaskIntoConstraints = false
  1016. footerLinkButtons.append(button)
  1017. container.addSubview(button)
  1018. var constraints: [NSLayoutConstraint] = [
  1019. button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
  1020. button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  1021. ]
  1022. if showsTrailingDivider {
  1023. let divider = footerDivider()
  1024. container.addSubview(divider)
  1025. constraints.append(contentsOf: [
  1026. divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
  1027. divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
  1028. ])
  1029. }
  1030. NSLayoutConstraint.activate(constraints)
  1031. return (container, button)
  1032. }
  1033. private enum PrimaryFooterSubscriptionTitle {
  1034. static var manage: String { L("Manage Subscription") }
  1035. static var continueFree: String { L("Continue with free plan") }
  1036. }
  1037. private func subscriptionPrimaryFooterTitle() -> String {
  1038. subscriptionStore.isProActive ? PrimaryFooterSubscriptionTitle.manage : PrimaryFooterSubscriptionTitle.continueFree
  1039. }
  1040. private func updateSubscriptionPrimaryFooter() {
  1041. subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
  1042. }
  1043. private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
  1044. let image = NSImageView()
  1045. image.translatesAutoresizingMaskIntoConstraints = false
  1046. image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  1047. image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
  1048. image.contentTintColor = Theme.primaryText
  1049. let titleLabel = NSTextField(labelWithString: title)
  1050. titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
  1051. titleLabel.textColor = Theme.primaryText
  1052. let subtitleLabel = NSTextField(labelWithString: subtitle)
  1053. subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
  1054. subtitleLabel.textColor = Theme.secondaryText
  1055. let textStack = NSStackView(views: [titleLabel, subtitleLabel])
  1056. textStack.orientation = .vertical
  1057. textStack.spacing = 2
  1058. textStack.alignment = .leading
  1059. let stack = NSStackView(views: [image, textStack])
  1060. stack.orientation = .horizontal
  1061. stack.spacing = 8
  1062. stack.alignment = .leading
  1063. stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
  1064. stack.wantsLayer = true
  1065. stack.layer?.backgroundColor = NSColor.clear.cgColor
  1066. return stack
  1067. }
  1068. private func footerDivider() -> NSBox {
  1069. let divider = NSBox()
  1070. divider.boxType = .separator
  1071. divider.borderColor = Theme.divider
  1072. divider.translatesAutoresizingMaskIntoConstraints = false
  1073. divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
  1074. divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
  1075. return divider
  1076. }
  1077. @objc private func didTapSelectPlan(_ sender: NSButton) {
  1078. guard let planKey = sender.identifier?.rawValue else { return }
  1079. Task { await purchasePlan(planKey: planKey) }
  1080. }
  1081. @objc private func didTapPrimaryFooterSubscriptionAction(_ sender: NSButton) {
  1082. let userTappedManage = (sender.title == PrimaryFooterSubscriptionTitle.manage)
  1083. Task { @MainActor [weak self] in
  1084. guard let self else { return }
  1085. await subscriptionStore.refreshEntitlements(deep: true)
  1086. updateSubscriptionPrimaryFooter()
  1087. let active = subscriptionStore.isProActive
  1088. if active || userTappedManage {
  1089. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
  1090. NSWorkspace.shared.open(url)
  1091. return
  1092. }
  1093. // Non-pro: dismiss paywall and return to the home (dashboard) window.
  1094. dismissPremiumSheetFromParentIfNeeded()
  1095. }
  1096. }
  1097. @objc private func didTapRestorePurchases() {
  1098. Task { await restorePurchases() }
  1099. }
  1100. @objc private func didTapFooterPrivacyPolicy() {
  1101. AppLegalURLs.openInSafari(AppLegalURLs.privacyPolicy)
  1102. }
  1103. @objc private func didTapFooterTermsOfServices() {
  1104. AppLegalURLs.openInSafari(AppLegalURLs.termsOfUse)
  1105. }
  1106. @objc private func didTapFooterSupport() {
  1107. AppLegalURLs.openInSafari(AppLegalURLs.support)
  1108. }
  1109. private func loadStoreProducts() async {
  1110. applyStorePricing()
  1111. await subscriptionStore.ensureProductsLoaded()
  1112. applyStorePricing()
  1113. updateSubscriptionPrimaryFooter()
  1114. updatePremiumCloseButtonVisibility()
  1115. await subscriptionStore.refreshEntitlements(deep: true)
  1116. updateSubscriptionPrimaryFooter()
  1117. updatePremiumCloseButtonVisibility()
  1118. }
  1119. private func applyStorePricing() {
  1120. for plan in plans {
  1121. guard let fields = planPriceFields[plan.id] else { continue }
  1122. guard let product = subscriptionStore.product(forPlanKey: plan.id) else {
  1123. fields.price.stringValue = Self.unloadedPricePlaceholder
  1124. continue
  1125. }
  1126. fields.price.stringValue = product.displayPrice
  1127. if let period = product.subscription?.subscriptionPeriod {
  1128. fields.period.stringValue = periodSuffix(for: period)
  1129. }
  1130. }
  1131. }
  1132. private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
  1133. let value = period.value
  1134. switch period.unit {
  1135. case .day: return value == 1 ? L("/ day") : String(format: L("/ %d days"), value)
  1136. case .week: return value == 1 ? L("/ week") : String(format: L("/ %d weeks"), value)
  1137. case .month: return value == 1 ? L("/ month") : String(format: L("/ %d months"), value)
  1138. case .year: return value == 1 ? L("/ year") : String(format: L("/ %d years"), value)
  1139. @unknown default: return ""
  1140. }
  1141. }
  1142. private func setPurchasing(_ isPurchasing: Bool) {
  1143. for button in planPurchaseButtons.values {
  1144. button.isEnabled = !isPurchasing
  1145. }
  1146. }
  1147. private func purchasePlan(planKey: String) async {
  1148. setPurchasing(true)
  1149. defer { setPurchasing(false) }
  1150. do {
  1151. let completed = try await subscriptionStore.purchase(planKey: planKey)
  1152. guard completed else { return }
  1153. AppRatingCoordinator.shared.scheduleReviewAfterSubscriptionPurchase()
  1154. let alert = NSAlert()
  1155. alert.messageText = L("You're subscribed")
  1156. alert.informativeText = L("Thank you — Pro features are now available.")
  1157. alert.alertStyle = .informational
  1158. alert.addButton(withTitle: L("OK"))
  1159. if let window = view.window {
  1160. alert.beginSheetModal(for: window) { [weak self] _ in
  1161. self?.dismissPremiumSheetFromParentIfNeeded()
  1162. }
  1163. } else {
  1164. alert.runModal()
  1165. dismissPremiumSheetFromParentIfNeeded()
  1166. }
  1167. } catch {
  1168. await MainActor.run {
  1169. self.presentPurchaseError(error, context: .purchase)
  1170. }
  1171. }
  1172. }
  1173. private func restorePurchases() async {
  1174. setPurchasing(true)
  1175. defer { setPurchasing(false) }
  1176. do {
  1177. try await subscriptionStore.restorePurchases()
  1178. let active = subscriptionStore.isProActive
  1179. let alert = NSAlert()
  1180. if active {
  1181. alert.messageText = L("Purchases restored")
  1182. alert.informativeText = L("Your subscription is active.")
  1183. } else {
  1184. alert.messageText = L("No subscription found")
  1185. alert.informativeText = L("There was nothing to restore for this Apple ID.")
  1186. }
  1187. alert.alertStyle = .informational
  1188. alert.addButton(withTitle: L("OK"))
  1189. if let window = view.window {
  1190. alert.beginSheetModal(for: window) { [weak self] _ in
  1191. if active {
  1192. self?.dismissPremiumSheetFromParentIfNeeded()
  1193. }
  1194. }
  1195. } else {
  1196. alert.runModal()
  1197. if active {
  1198. dismissPremiumSheetFromParentIfNeeded()
  1199. }
  1200. }
  1201. } catch {
  1202. await MainActor.run {
  1203. self.presentPurchaseError(error, context: .restore)
  1204. }
  1205. }
  1206. }
  1207. private func presentPurchaseError(
  1208. _ error: Error,
  1209. context: UserFacingErrorMessage.PurchaseContext
  1210. ) {
  1211. let alert = NSAlert()
  1212. alert.messageText = L("Something went wrong")
  1213. alert.informativeText = UserFacingErrorMessage.purchaseFailure(error, context: context)
  1214. alert.alertStyle = .warning
  1215. alert.addButton(withTitle: L("OK"))
  1216. if let window = view.window {
  1217. alert.beginSheetModal(for: window)
  1218. } else {
  1219. alert.runModal()
  1220. }
  1221. }
  1222. private func applyLocalizedStrings() {
  1223. view.window?.title = L("Premium Plans")
  1224. premiumTitleLabel?.stringValue = L("Upgrade to Pro")
  1225. premiumSubtitleLabel?.stringValue = L("Unlock unlimited access to premium tools and boost your productivity.")
  1226. for target in pricingCardTargets {
  1227. guard let plan = plans.first(where: { $0.id == target.planId }) else { continue }
  1228. target.titleLabel.stringValue = plan.title
  1229. target.subtitleLabel.stringValue = plan.subtitle
  1230. if subscriptionStore.product(forPlanKey: plan.id) == nil {
  1231. target.periodLabel.stringValue = plan.period
  1232. }
  1233. target.billedPillLabel?.stringValue = plan.billedPill
  1234. target.billedPillLabel?.isHidden = plan.billedPill.isEmpty
  1235. for (index, label) in target.featureLabels.enumerated() where index < plan.features.count {
  1236. let font = label.font ?? .systemFont(ofSize: 13, weight: .medium)
  1237. let color = label.textColor ?? Theme.primaryText
  1238. label.attributedStringValue = AppLayoutDirection.attributedString(
  1239. plan.features[index],
  1240. font: font,
  1241. color: color
  1242. )
  1243. AppLayoutDirection.configureTextField(label)
  1244. }
  1245. target.purchaseButton.title = String(format: L("Get %@"), plan.title)
  1246. }
  1247. if let trustBadgesRow {
  1248. let trustData: [(String, String)] = [
  1249. (L("Secure Payments"), L("Your payment is 100% secure.")),
  1250. (L("Cancel Anytime"), L("No commitment, cancel anytime.")),
  1251. (L("24/7 Support"), L("We're here to help you anytime.")),
  1252. (L("Privacy First"), L("Your data is safe with us."))
  1253. ]
  1254. for (index, subview) in trustBadgesRow.arrangedSubviews.enumerated() {
  1255. guard let badge = subview as? NSStackView, index < trustData.count else { continue }
  1256. for case let textStack as NSStackView in badge.arrangedSubviews {
  1257. let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
  1258. if labels.count >= 2 {
  1259. labels[0].stringValue = trustData[index].0
  1260. labels[1].stringValue = trustData[index].1
  1261. }
  1262. }
  1263. }
  1264. }
  1265. let footerTitles = [
  1266. subscriptionPrimaryFooterTitle(),
  1267. L("Restore Purchase"),
  1268. L("Privacy Policy"),
  1269. L("Terms of Use"),
  1270. L("Support")
  1271. ]
  1272. for (index, button) in footerLinkButtons.enumerated() where index < footerTitles.count {
  1273. button.title = footerTitles[index]
  1274. }
  1275. updateSubscriptionPrimaryFooter()
  1276. applyStorePricing()
  1277. applyLayoutDirection()
  1278. }
  1279. private func dismissPremiumSheetFromParentIfNeeded() {
  1280. guard let sheet = view.window, let parent = sheet.sheetParent else { return }
  1281. parent.endSheet(sheet)
  1282. }
  1283. @objc private func didTapClose() {
  1284. guard let window = view.window else { return }
  1285. if let parent = window.sheetParent {
  1286. parent.endSheet(window)
  1287. return
  1288. }
  1289. window.close()
  1290. }
  1291. private func applyCurrentAppearance() {
  1292. view.window?.backgroundColor = PremiumPlansWindowController.paywallSheetBackground
  1293. pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
  1294. premiumTitleLabel?.textColor = Theme.primaryText
  1295. premiumSubtitleLabel?.textColor = Theme.secondaryText
  1296. for target in pricingCardTargets {
  1297. target.card.updateBorderColors(base: Theme.cardBorder, hover: Theme.accent)
  1298. target.card.layer?.backgroundColor = Theme.cardBackground.cgColor
  1299. target.iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1300. target.planIconView.contentTintColor = planIconTint(planId: target.planId)
  1301. target.titleLabel.textColor = Theme.primaryText
  1302. target.subtitleLabel.textColor = Theme.secondaryText
  1303. target.priceLabel.textColor = Theme.primaryText
  1304. target.periodLabel.textColor = Theme.secondaryText
  1305. target.billingLabel?.textColor = Theme.secondaryText
  1306. target.divider.borderColor = Theme.divider
  1307. for label in target.featureLabels {
  1308. label.textColor = Theme.primaryText
  1309. }
  1310. for icon in target.featureIcons {
  1311. icon.contentTintColor = Theme.iconTint
  1312. }
  1313. target.purchaseButton.refreshAppearance()
  1314. }
  1315. if let trustBadgesRow {
  1316. trustBadgesRow.layer?.backgroundColor = Theme.bottomStrip.cgColor
  1317. trustBadgesRow.layer?.borderColor = Theme.divider.cgColor
  1318. for case let badge as NSStackView in trustBadgesRow.arrangedSubviews {
  1319. for case let image as NSImageView in badge.arrangedSubviews {
  1320. image.contentTintColor = Theme.primaryText
  1321. }
  1322. for case let textStack as NSStackView in badge.arrangedSubviews {
  1323. let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
  1324. if labels.count >= 2 {
  1325. labels[0].textColor = Theme.primaryText
  1326. labels[1].textColor = Theme.secondaryText
  1327. }
  1328. }
  1329. }
  1330. }
  1331. for button in footerLinkButtons {
  1332. button.contentTintColor = Theme.secondaryText
  1333. }
  1334. premiumCloseButton?.refreshAppearance(hovered: false)
  1335. applyLayoutDirection()
  1336. }
  1337. private func planIconTint(planId: String) -> NSColor {
  1338. switch planId {
  1339. case "monthly": Theme.accent
  1340. case "yearly": Theme.successText
  1341. default: Theme.iconTint
  1342. }
  1343. }
  1344. }
  1345. private extension NSView {
  1346. func enclosingFeatureListScrollView() -> NSScrollView? {
  1347. var node: NSView? = superview
  1348. while let view = node {
  1349. if let scroll = view as? NSScrollView, scroll.documentView?.subviews.contains(where: { $0 === self }) == true {
  1350. return scroll
  1351. }
  1352. node = view.superview
  1353. }
  1354. return nil
  1355. }
  1356. }