| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436 |
- import Cocoa
- import StoreKit
- final class PremiumPlansWindowController: NSWindowController {
- /// Matches `PremiumPlansViewController.Theme.pageStart` so the window backing fills sheet corners.
- static var paywallSheetBackground: NSColor { PremiumPlansViewController.Theme.pageStart }
- init() {
- let viewController = PremiumPlansViewController()
- let window = NSWindow(contentViewController: viewController)
- window.title = L("Premium Plans")
- // Borderless avoids titled-window chrome: its rounded titlebar frame often leaves dark wedges at
- // the corners when combined with a custom full-bleed paywall (this window is only shown as a sheet).
- window.styleMask = [.borderless, .closable, .resizable]
- window.isOpaque = true
- window.backgroundColor = Self.paywallSheetBackground
- window.setContentSize(NSSize(width: 1160, height: 760))
- window.minSize = NSSize(width: 980, height: 680)
- window.isRestorable = false
- window.center()
- super.init(window: window)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- /// Loads StoreKit prices into the paywall view before the sheet is shown (avoids "—" placeholders flashing in).
- @MainActor
- func prepareForPresentation() async {
- _ = window
- guard let viewController = window?.contentViewController as? PremiumPlansViewController else { return }
- await viewController.prepareStorePricingForDisplay()
- }
- }
- private final class PremiumPlansViewController: NSViewController {
- private final class HoverPricingCardView: NSView {
- private var baseBorderColor: NSColor
- private var hoverBorderColor: NSColor
- private var trackingAreaRef: NSTrackingArea?
- private var isHovered = false
- init(baseBorderColor: NSColor, hoverBorderColor: NSColor) {
- self.baseBorderColor = baseBorderColor
- self.hoverBorderColor = hoverBorderColor
- super.init(frame: .zero)
- wantsLayer = true
- layer?.cornerRadius = 16
- applyHoverStyle(isHovered: false, animated: false)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
- let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- isHovered = true
- applyHoverStyle(isHovered: true, animated: true)
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- isHovered = false
- applyHoverStyle(isHovered: false, animated: true)
- }
- func updateBorderColors(base: NSColor, hover: NSColor) {
- baseBorderColor = base
- hoverBorderColor = hover
- applyHoverStyle(isHovered: isHovered, animated: false)
- }
- private func applyHoverStyle(isHovered: Bool, animated: Bool) {
- guard let layer else { return }
- let updates = {
- layer.borderWidth = isHovered ? 2 : 1
- layer.borderColor = (isHovered ? self.hoverBorderColor : self.baseBorderColor).cgColor
- layer.shadowColor = self.hoverBorderColor.withAlphaComponent(0.35).cgColor
- layer.shadowOpacity = isHovered ? 0.22 : 0
- layer.shadowRadius = isHovered ? 14 : 0
- layer.shadowOffset = .init(width: 0, height: -2)
- }
- if animated {
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.16
- updates()
- }
- } else {
- updates()
- }
- }
- }
- /// Footer text actions: accent color + pointing hand on hover (matches pricing-card tracking behavior).
- private final class FooterLinkButton: NSButton {
- private var trackingAreaRef: NSTrackingArea?
- private var didPushCursor = false
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
- let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- setHoverVisuals(hovered: true)
- if !didPushCursor {
- NSCursor.pointingHand.push()
- didPushCursor = true
- }
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- setHoverVisuals(hovered: false)
- if didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- }
- override func viewWillMove(toWindow newWindow: NSWindow?) {
- super.viewWillMove(toWindow: newWindow)
- if newWindow == nil, didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- if newWindow == nil {
- setHoverVisuals(hovered: false, animated: false)
- }
- }
- private func setHoverVisuals(hovered: Bool, animated: Bool = true) {
- let color = hovered ? Theme.accent : Theme.secondaryText
- if animated {
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.15
- self.animator().contentTintColor = color
- }
- } else {
- contentTintColor = color
- }
- }
- }
- /// Purchase CTAs: fill/border/shadow + pointing hand on hover.
- private final class PlanPurchaseHoverButton: NSButton {
- private var trackingAreaRef: NSTrackingArea?
- private var didPushCursor = false
- private let isPrimaryStyle: Bool
- private static let primaryFill = NSColor(srgbRed: 189 / 255, green: 52 / 255, blue: 255 / 255, alpha: 1)
- private static let primaryFillHover = NSColor(srgbRed: 205 / 255, green: 88 / 255, blue: 255 / 255, alpha: 1)
- init(planId: String, title: String, isPrimaryStyle: Bool, target: AnyObject?, action: Selector) {
- self.isPrimaryStyle = isPrimaryStyle
- super.init(frame: .zero)
- identifier = NSUserInterfaceItemIdentifier(planId)
- self.title = title
- self.target = target
- self.action = action
- isBordered = false
- bezelStyle = .rounded
- font = .systemFont(ofSize: 14, weight: .semibold)
- wantsLayer = true
- layer?.cornerRadius = 12
- focusRingType = .none
- translatesAutoresizingMaskIntoConstraints = false
- applyBaseStyle(hovered: false)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- override var isEnabled: Bool {
- didSet {
- if !isEnabled {
- applyBaseStyle(hovered: false, animated: true)
- if didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- }
- }
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
- let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- guard isEnabled else { return }
- applyBaseStyle(hovered: true, animated: true)
- if !didPushCursor {
- NSCursor.pointingHand.push()
- didPushCursor = true
- }
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- applyBaseStyle(hovered: false, animated: true)
- if didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- }
- override func viewWillMove(toWindow newWindow: NSWindow?) {
- super.viewWillMove(toWindow: newWindow)
- if newWindow == nil, didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- if newWindow == nil {
- applyBaseStyle(hovered: false, animated: false)
- }
- }
- func refreshAppearance() {
- applyBaseStyle(hovered: false, animated: false)
- }
- private func applyBaseStyle(hovered: Bool, animated: Bool = true) {
- let updates = {
- if self.isPrimaryStyle {
- self.layer?.backgroundColor = (hovered ? Self.primaryFillHover : Self.primaryFill).cgColor
- self.layer?.borderColor = Theme.accent.cgColor
- self.layer?.borderWidth = hovered ? 2 : 1
- self.contentTintColor = .white
- self.layer?.shadowColor = Self.primaryFill.cgColor
- self.layer?.shadowOpacity = hovered ? 0.28 : 0
- self.layer?.shadowRadius = hovered ? 12 : 0
- self.layer?.shadowOffset = CGSize(width: 0, height: -2)
- } else {
- let baseFill = Theme.mutedButtonFill
- let hoverFill = baseFill.blended(withFraction: 0.22, of: Theme.accent) ?? baseFill
- self.layer?.backgroundColor = (hovered ? hoverFill : baseFill).cgColor
- self.layer?.borderColor = (hovered ? Theme.accent : Theme.divider).cgColor
- self.layer?.borderWidth = hovered ? 2 : 1
- self.contentTintColor = Theme.primaryText
- self.layer?.shadowColor = Theme.accent.withAlphaComponent(0.35).cgColor
- self.layer?.shadowOpacity = hovered ? 0.18 : 0
- self.layer?.shadowRadius = hovered ? 10 : 0
- self.layer?.shadowOffset = CGSize(width: 0, height: -2)
- }
- }
- if animated {
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.16
- updates()
- }
- } else {
- updates()
- }
- }
- }
- /// Close control: subtle lift + accent tint on hover.
- private final class PremiumCloseHoverButton: NSButton {
- private var trackingAreaRef: NSTrackingArea?
- private var didPushCursor = false
- init(target: AnyObject?, action: Selector) {
- super.init(frame: .zero)
- self.target = target
- self.action = action
- isBordered = false
- wantsLayer = true
- layer?.cornerRadius = 15
- bezelStyle = .regularSquare
- image = NSImage(systemSymbolName: "xmark", accessibilityDescription: L("Close"))
- imageScaling = .scaleProportionallyDown
- focusRingType = .none
- translatesAutoresizingMaskIntoConstraints = false
- applyStyle(hovered: false, animated: false)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect]
- let area = NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- applyStyle(hovered: true, animated: true)
- if !didPushCursor {
- NSCursor.pointingHand.push()
- didPushCursor = true
- }
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- applyStyle(hovered: false, animated: true)
- if didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- }
- override func viewWillMove(toWindow newWindow: NSWindow?) {
- super.viewWillMove(toWindow: newWindow)
- if newWindow == nil, didPushCursor {
- NSCursor.pop()
- didPushCursor = false
- }
- if newWindow == nil {
- applyStyle(hovered: false, animated: false)
- }
- }
- func refreshAppearance(hovered: Bool) {
- applyStyle(hovered: hovered, animated: false)
- }
- private func applyStyle(hovered: Bool, animated: Bool) {
- let updates = {
- self.layer?.backgroundColor = (hovered
- ? Theme.closeButtonBackgroundHover
- : Theme.closeButtonBackground).cgColor
- self.layer?.borderColor = (hovered ? Theme.accent.withAlphaComponent(0.45) : Theme.divider).cgColor
- self.layer?.borderWidth = hovered ? 1.5 : 1
- self.contentTintColor = hovered ? Theme.accent : Theme.secondaryText
- self.layer?.shadowColor = Theme.accent.withAlphaComponent(0.25).cgColor
- self.layer?.shadowOpacity = hovered ? 0.2 : 0
- self.layer?.shadowRadius = hovered ? 8 : 0
- self.layer?.shadowOffset = CGSize(width: 0, height: -1)
- }
- if animated {
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.15
- updates()
- }
- } else {
- updates()
- }
- }
- }
- /// Shown until StoreKit returns localized `Product.displayPrice` (never use hardcoded currency amounts).
- private static let unloadedPricePlaceholder = "—"
- private struct Plan {
- let id: String
- let title: String
- let subtitle: String
- let period: String
- let billedPill: String
- let billedLine: String
- let crossedPrice: String?
- let savingsText: String?
- let features: [String]
- let iconName: String
- let iconTint: NSColor
- let highlight: Bool
- }
- fileprivate enum Theme {
- static var pageStart: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.pageBackground
- : NSColor(srgbRed: 249 / 255, green: 252 / 255, blue: 255 / 255, alpha: 1)
- }
- static var pageEnd: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.loadingPageBackgroundBottom
- : NSColor(srgbRed: 238 / 255, green: 244 / 255, blue: 255 / 255, alpha: 1)
- }
- static var cardBackground: NSColor { AppDashboardTheme.cardBackground }
- static var primaryText: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.primaryText
- : NSColor(srgbRed: 27 / 255, green: 38 / 255, blue: 79 / 255, alpha: 1)
- }
- static var secondaryText: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.secondaryText
- : NSColor(srgbRed: 108 / 255, green: 120 / 255, blue: 157 / 255, alpha: 1)
- }
- static var cardBorder: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.border
- : NSColor(srgbRed: 198 / 255, green: 216 / 255, blue: 255 / 255, alpha: 1)
- }
- static var accent: NSColor { AppDashboardTheme.brandBlue }
- static var accentHover: NSColor { AppDashboardTheme.brandBlueHover }
- static var mutedButtonFill: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.profileFieldFill
- : NSColor(srgbRed: 238 / 255, green: 243 / 255, blue: 252 / 255, alpha: 1)
- }
- static var bottomStrip: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.proCardFill
- : NSColor(srgbRed: 244 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1)
- }
- static var divider: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.border
- : NSColor(srgbRed: 218 / 255, green: 228 / 255, blue: 247 / 255, alpha: 1)
- }
- static var successText: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.welcomeHeroHeadingBlue
- : NSColor(srgbRed: 21 / 255, green: 154 / 255, blue: 220 / 255, alpha: 1)
- }
- static var iconTint: NSColor { AppDashboardTheme.brandBlue }
- static var closeButtonBackground: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.cardBackground
- : NSColor.white.withAlphaComponent(0.92)
- }
- static var closeButtonBackgroundHover: NSColor {
- AppDashboardTheme.isDark
- ? AppDashboardTheme.neutralHoverFill
- : NSColor.white.withAlphaComponent(0.98)
- }
- }
- private struct PricingCardAppearanceTarget {
- let card: HoverPricingCardView
- let iconWell: NSView
- let planIconView: NSImageView
- let planId: String
- let titleLabel: NSTextField
- let subtitleLabel: NSTextField
- let priceLabel: NSTextField
- let periodLabel: NSTextField
- let billingLabel: NSTextField?
- let divider: NSBox
- let featureLabels: [NSTextField]
- let featureIcons: [NSImageView]
- let purchaseButton: PlanPurchaseHoverButton
- let billedPillLabel: NSTextField?
- }
- private enum FeatureListMetrics {
- static let rowSpacing = CGFloat(8)
- static let iconLabelSpacing = CGFloat(8)
- static let edgeInsets = NSEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
- /// Caps feature list height so pricing cards do not push the footer off-screen.
- static let maxScrollHeight = CGFloat(168)
- }
- private let subscriptionStore = SubscriptionStore.shared
- private var planPriceFields: [String: (price: NSTextField, period: NSTextField)] = [:]
- private var planPurchaseButtons: [String: NSButton] = [:]
- private var subscriptionPrimaryFooterButton: NSButton?
- private var premiumCloseButton: PremiumCloseHoverButton?
- private var subscriptionStatusObservation: NSObjectProtocol?
- private var appearanceObserver: NSObjectProtocol?
- private var languageObserver: NSObjectProtocol?
- private var storeProductsLoadTask: Task<Void, Never>?
- /// Core Pro capabilities shown on every pricing card (replaces generic “All premium features”).
- private var proCapabilityFeatures: [String] {
- [
- L("Unlimited AI job search on Home"),
- L("Save jobs & open listings in-app"),
- L("CV Maker, profiles & PDF export"),
- L("Role, company & skill shortcuts")
- ]
- }
- private var plans: [Plan] {
- [
- Plan(
- id: "weekly",
- title: L("Weekly"),
- subtitle: L("Flexible and commitment-free"),
- period: L("/ week"),
- billedPill: "",
- billedLine: "",
- crossedPrice: nil,
- savingsText: nil,
- features: proCapabilityFeatures + [
- L("Perfect for short-term job hunts"),
- L("Cancel anytime")
- ],
- iconName: "paperplane.fill",
- iconTint: Theme.iconTint,
- highlight: false
- ),
- Plan(
- id: "monthly",
- title: L("Monthly"),
- subtitle: L("Balanced for regular productivity"),
- period: L("/ month"),
- billedPill: "",
- billedLine: "",
- crossedPrice: nil,
- savingsText: nil,
- features: proCapabilityFeatures + [
- L("Best for regular job seekers"),
- L("Priority support")
- ],
- iconName: "bolt.fill",
- iconTint: Theme.accent,
- highlight: true
- ),
- Plan(
- id: "yearly",
- title: L("Yearly"),
- subtitle: L("Best value for long-term users"),
- period: L("/ year"),
- billedPill: L("3 days free trial"),
- billedLine: "",
- crossedPrice: nil,
- savingsText: nil,
- features: proCapabilityFeatures + [
- L("Lowest effective monthly cost"),
- L("Ideal for long-term use")
- ],
- iconName: "crown.fill",
- iconTint: Theme.successText,
- highlight: false
- )
- ]
- }
- private let pageGradient = CAGradientLayer()
- private var premiumTitleLabel: NSTextField?
- private var premiumSubtitleLabel: NSTextField?
- private var pricingCardTargets: [PricingCardAppearanceTarget] = []
- private weak var trustBadgesRow: NSStackView?
- private var footerLinkButtons: [FooterLinkButton] = []
- deinit {
- if let subscriptionStatusObservation {
- NotificationCenter.default.removeObserver(subscriptionStatusObservation)
- }
- if let appearanceObserver {
- NotificationCenter.default.removeObserver(appearanceObserver)
- }
- if let languageObserver {
- NotificationCenter.default.removeObserver(languageObserver)
- }
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- appearanceObserver = NotificationCenter.default.addObserver(
- forName: AppAppearanceManager.didChangeNotification,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- self?.applyCurrentAppearance()
- }
- languageObserver = NotificationCenter.default.addObserver(
- forName: AppLanguageManager.didChangeNotification,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- self?.applyLocalizedStrings()
- }
- subscriptionStatusObservation = NotificationCenter.default.addObserver(
- forName: .subscriptionStatusDidChange,
- object: nil,
- queue: .main
- ) { [weak self] _ in
- Task { @MainActor in
- await self?.subscriptionStore.ensureProductsLoaded()
- self?.applyStorePricing()
- self?.updateSubscriptionPrimaryFooter()
- self?.updatePremiumCloseButtonVisibility()
- }
- }
- applyStorePricing()
- storeProductsLoadTask = Task { @MainActor [weak self] in
- await self?.loadStoreProducts()
- self?.storeProductsLoadTask = nil
- }
- }
- /// Ensures localized prices are on screen; reuses an in-flight load started from `viewDidLoad`.
- @MainActor
- func prepareStorePricingForDisplay() async {
- applyStorePricing()
- if let storeProductsLoadTask {
- await storeProductsLoadTask.value
- applyStorePricing()
- return
- }
- await subscriptionStore.ensureProductsLoaded()
- applyStorePricing()
- }
- override func viewDidLayout() {
- super.viewDidLayout()
- pageGradient.frame = view.bounds
- }
- override func loadView() {
- view = NSView()
- view.wantsLayer = true
- pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
- pageGradient.startPoint = CGPoint(x: 0, y: 1)
- pageGradient.endPoint = CGPoint(x: 1, y: 0)
- view.layer?.addSublayer(pageGradient)
- setupLayout()
- applyCurrentAppearance()
- }
- private func setupLayout() {
- let closeButton = PremiumCloseHoverButton(target: self, action: #selector(didTapClose))
- let crownIcon = NSImageView()
- crownIcon.translatesAutoresizingMaskIntoConstraints = false
- crownIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
- crownIcon.image = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: nil)
- crownIcon.contentTintColor = NSColor(srgbRed: 254 / 255, green: 214 / 255, blue: 92 / 255, alpha: 1)
- let title = NSTextField(labelWithString: L("Upgrade to Pro"))
- title.font = .systemFont(ofSize: 40, weight: .semibold)
- title.textColor = Theme.primaryText
- title.alignment = .center
- premiumTitleLabel = title
- let subtitle = NSTextField(labelWithString: L("Unlock unlimited access to premium tools and boost your productivity."))
- subtitle.font = .systemFont(ofSize: 14, weight: .regular)
- subtitle.textColor = Theme.secondaryText
- subtitle.alignment = .center
- premiumSubtitleLabel = subtitle
- pricingCardTargets = []
- let cardsRow = NSStackView(views: plans.map(makePricingCard(_:)))
- cardsRow.orientation = .horizontal
- cardsRow.spacing = 14
- cardsRow.alignment = .top
- cardsRow.distribution = .fillEqually
- cardsRow.translatesAutoresizingMaskIntoConstraints = false
- let trustRow = makeTrustRow()
- let footerRow = makeFooterRow()
- let headerStack = NSStackView(views: [crownIcon, title, subtitle])
- headerStack.orientation = .vertical
- headerStack.spacing = 10
- headerStack.alignment = .centerX
- headerStack.translatesAutoresizingMaskIntoConstraints = false
- let bodyStack = NSStackView(views: [cardsRow, trustRow])
- bodyStack.orientation = .vertical
- bodyStack.spacing = 16
- bodyStack.alignment = .centerX
- bodyStack.translatesAutoresizingMaskIntoConstraints = false
- let scrollView = NSScrollView()
- scrollView.hasVerticalScroller = true
- scrollView.autohidesScrollers = true
- scrollView.drawsBackground = false
- scrollView.borderType = .noBorder
- scrollView.translatesAutoresizingMaskIntoConstraints = false
- let scrollDocument = NSView()
- scrollDocument.translatesAutoresizingMaskIntoConstraints = false
- scrollView.documentView = scrollDocument
- scrollDocument.addSubview(bodyStack)
- view.addSubview(headerStack)
- view.addSubview(scrollView)
- view.addSubview(footerRow)
- view.addSubview(closeButton)
- let scrollClip = scrollView.contentView
- NSLayoutConstraint.activate([
- headerStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
- headerStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
- headerStack.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
- scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
- scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
- scrollView.topAnchor.constraint(equalTo: headerStack.bottomAnchor, constant: 12),
- scrollView.bottomAnchor.constraint(equalTo: footerRow.topAnchor, constant: -12),
- footerRow.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 24),
- footerRow.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -24),
- footerRow.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16),
- footerRow.heightAnchor.constraint(greaterThanOrEqualToConstant: 32),
- scrollDocument.leadingAnchor.constraint(equalTo: scrollClip.leadingAnchor),
- scrollDocument.trailingAnchor.constraint(equalTo: scrollClip.trailingAnchor),
- scrollDocument.topAnchor.constraint(equalTo: scrollClip.topAnchor),
- scrollDocument.widthAnchor.constraint(equalTo: scrollClip.widthAnchor),
- scrollDocument.bottomAnchor.constraint(equalTo: bodyStack.bottomAnchor, constant: 8),
- bodyStack.leadingAnchor.constraint(equalTo: scrollDocument.leadingAnchor),
- bodyStack.trailingAnchor.constraint(equalTo: scrollDocument.trailingAnchor),
- bodyStack.topAnchor.constraint(equalTo: scrollDocument.topAnchor, constant: 4),
- bodyStack.widthAnchor.constraint(equalTo: scrollDocument.widthAnchor),
- cardsRow.widthAnchor.constraint(equalTo: bodyStack.widthAnchor),
- trustRow.widthAnchor.constraint(equalTo: bodyStack.widthAnchor),
- closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
- closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -14),
- closeButton.widthAnchor.constraint(equalToConstant: 30),
- closeButton.heightAnchor.constraint(equalToConstant: 30),
- crownIcon.heightAnchor.constraint(equalToConstant: 20)
- ])
- premiumCloseButton = closeButton
- updatePremiumCloseButtonVisibility()
- }
- private func updatePremiumCloseButtonVisibility() {
- premiumCloseButton?.isHidden = !subscriptionStore.isProActive
- }
- private func makePricingCard(_ plan: Plan) -> NSView {
- let card = HoverPricingCardView(baseBorderColor: Theme.cardBorder, hoverBorderColor: Theme.accent)
- card.translatesAutoresizingMaskIntoConstraints = false
- card.layer?.backgroundColor = Theme.cardBackground.cgColor
- let iconWell = NSView()
- iconWell.translatesAutoresizingMaskIntoConstraints = false
- iconWell.wantsLayer = true
- iconWell.layer?.cornerRadius = 10
- iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
- iconWell.widthAnchor.constraint(equalToConstant: 24).isActive = true
- iconWell.heightAnchor.constraint(equalToConstant: 24).isActive = true
- let icon = NSImageView()
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
- icon.image = NSImage(systemSymbolName: plan.iconName, accessibilityDescription: nil)
- icon.contentTintColor = plan.iconTint
- iconWell.addSubview(icon)
- NSLayoutConstraint.activate([
- icon.centerXAnchor.constraint(equalTo: iconWell.centerXAnchor),
- icon.centerYAnchor.constraint(equalTo: iconWell.centerYAnchor)
- ])
- let titleLabel = NSTextField(labelWithString: plan.title)
- titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
- titleLabel.textColor = Theme.primaryText
- titleLabel.alignment = .center
- let subtitleLabel = NSTextField(labelWithString: plan.subtitle)
- subtitleLabel.font = .systemFont(ofSize: 12, weight: .regular)
- subtitleLabel.textColor = Theme.secondaryText
- subtitleLabel.alignment = .center
- let topRightTag = pillLabel(text: plan.billedPill, tint: Theme.bottomStrip, textColor: Theme.iconTint)
- topRightTag.isHidden = plan.billedPill.isEmpty
- topRightTag.font = .systemFont(ofSize: 10, weight: .bold)
- let priceLabel = NSTextField(labelWithString: Self.unloadedPricePlaceholder)
- priceLabel.font = .systemFont(ofSize: 18, weight: .semibold)
- priceLabel.textColor = Theme.primaryText
- let periodLabel = NSTextField(labelWithString: plan.period)
- periodLabel.font = .systemFont(ofSize: 13, weight: .medium)
- periodLabel.textColor = Theme.secondaryText
- let priceRow = NSStackView(views: [priceLabel, periodLabel])
- priceRow.orientation = .horizontal
- priceRow.spacing = 4
- priceRow.alignment = .firstBaseline
- let billingLabel = NSTextField(labelWithString: plan.billedLine)
- billingLabel.font = .systemFont(ofSize: 13, weight: .medium)
- billingLabel.textColor = Theme.secondaryText
- let inlinePriceInfo = inlinePriceInfoLabel(oldPrice: plan.crossedPrice, newPrice: plan.savingsText)
- let divider = NSBox()
- divider.boxType = .separator
- divider.translatesAutoresizingMaskIntoConstraints = false
- divider.borderColor = Theme.divider
- let featureRows = plan.features.map(makeFeatureRow(_:))
- let featuresStack = NSStackView(views: featureRows)
- featuresStack.orientation = .vertical
- featuresStack.spacing = FeatureListMetrics.rowSpacing
- featuresStack.alignment = .leading
- featuresStack.edgeInsets = FeatureListMetrics.edgeInsets
- featuresStack.setContentCompressionResistancePriority(.required, for: .vertical)
- featuresStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
- for row in featureRows {
- row.setContentCompressionResistancePriority(.required, for: .vertical)
- }
- let featuresScroll = makeFeatureListScroll(featuresStack: featuresStack)
- let selectButton = PlanPurchaseHoverButton(
- planId: plan.id,
- title: String(format: L("Get %@"), plan.title),
- isPrimaryStyle: plan.highlight,
- target: self,
- action: #selector(didTapSelectPlan)
- )
- planPurchaseButtons[plan.id] = selectButton
- planPriceFields[plan.id] = (priceLabel, periodLabel)
- selectButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
- let featureLabels = featureRows.compactMap { row -> NSTextField? in
- (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSTextField }.first
- }
- let featureIcons = featureRows.compactMap { row -> NSImageView? in
- (row as? NSStackView)?.arrangedSubviews.compactMap { $0 as? NSImageView }.first
- }
- pricingCardTargets.append(
- PricingCardAppearanceTarget(
- card: card,
- iconWell: iconWell,
- planIconView: icon,
- planId: plan.id,
- titleLabel: titleLabel,
- subtitleLabel: subtitleLabel,
- priceLabel: priceLabel,
- periodLabel: periodLabel,
- billingLabel: plan.billedLine.isEmpty ? nil : billingLabel,
- divider: divider,
- featureLabels: featureLabels,
- featureIcons: featureIcons,
- purchaseButton: selectButton,
- billedPillLabel: plan.billedPill.isEmpty ? nil : topRightTag
- )
- )
- var contentViews: [NSView] = [iconWell, titleLabel, subtitleLabel, priceRow]
- if !plan.billedLine.isEmpty {
- contentViews.append(billingLabel)
- }
- if plan.crossedPrice != nil, plan.savingsText != nil {
- contentViews.append(inlinePriceInfo)
- }
- contentViews.append(contentsOf: [divider, featuresScroll])
- let column = NSStackView(views: contentViews + [selectButton])
- column.orientation = .vertical
- column.spacing = 10
- column.alignment = .centerX
- column.distribution = .fill
- column.translatesAutoresizingMaskIntoConstraints = false
- card.addSubview(column)
- card.addSubview(topRightTag)
- NSLayoutConstraint.activate([
- divider.widthAnchor.constraint(equalTo: column.widthAnchor),
- featuresScroll.widthAnchor.constraint(equalTo: column.widthAnchor),
- column.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
- column.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
- column.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
- column.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -12),
- selectButton.widthAnchor.constraint(equalTo: column.widthAnchor),
- topRightTag.topAnchor.constraint(equalTo: card.topAnchor, constant: 12),
- topRightTag.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -12)
- ])
- return card
- }
- private func makeFeatureListScroll(featuresStack: NSStackView) -> NSScrollView {
- let scroll = NSScrollView()
- scroll.hasVerticalScroller = true
- scroll.autohidesScrollers = true
- scroll.drawsBackground = false
- scroll.borderType = .noBorder
- scroll.translatesAutoresizingMaskIntoConstraints = false
- let document = NSView()
- document.translatesAutoresizingMaskIntoConstraints = false
- featuresStack.translatesAutoresizingMaskIntoConstraints = false
- scroll.documentView = document
- document.addSubview(featuresStack)
- NSLayoutConstraint.activate([
- scroll.heightAnchor.constraint(equalToConstant: FeatureListMetrics.maxScrollHeight),
- document.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
- document.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
- document.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
- document.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
- document.bottomAnchor.constraint(equalTo: featuresStack.bottomAnchor, constant: FeatureListMetrics.edgeInsets.bottom),
- featuresStack.leadingAnchor.constraint(equalTo: document.leadingAnchor, constant: FeatureListMetrics.edgeInsets.left),
- featuresStack.trailingAnchor.constraint(equalTo: document.trailingAnchor, constant: -FeatureListMetrics.edgeInsets.right),
- featuresStack.topAnchor.constraint(equalTo: document.topAnchor, constant: FeatureListMetrics.edgeInsets.top),
- featuresStack.widthAnchor.constraint(equalTo: document.widthAnchor, constant: -(FeatureListMetrics.edgeInsets.left + FeatureListMetrics.edgeInsets.right))
- ])
- return scroll
- }
- private func makeFeatureRow(_ text: String) -> NSView {
- let icon = NSImageView()
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .bold)
- icon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil)
- icon.contentTintColor = Theme.iconTint
- icon.widthAnchor.constraint(equalToConstant: 14).isActive = true
- icon.heightAnchor.constraint(equalToConstant: 14).isActive = true
- icon.setContentHuggingPriority(.required, for: .horizontal)
- icon.setContentHuggingPriority(.required, for: .vertical)
- let label = NSTextField(wrappingLabelWithString: text)
- label.font = .systemFont(ofSize: 13, weight: .medium)
- label.textColor = Theme.primaryText
- label.alignment = .left
- label.lineBreakMode = .byWordWrapping
- label.maximumNumberOfLines = 0
- label.cell?.wraps = true
- label.cell?.isScrollable = false
- label.setContentCompressionResistancePriority(.required, for: .vertical)
- label.setContentHuggingPriority(.required, for: .vertical)
- label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- label.setContentHuggingPriority(.defaultLow, for: .horizontal)
- let row = NSStackView(views: [icon, label])
- row.orientation = .horizontal
- row.spacing = FeatureListMetrics.iconLabelSpacing
- row.alignment = .top
- row.distribution = .fill
- row.translatesAutoresizingMaskIntoConstraints = false
- return row
- }
- private func inlinePriceInfoLabel(oldPrice: String?, newPrice: String?) -> NSTextField {
- guard let oldPrice, let newPrice else {
- return NSTextField(labelWithString: "")
- }
- let full = NSMutableAttributedString()
- let oldAttributes: [NSAttributedString.Key: Any] = [
- .font: NSFont.systemFont(ofSize: 12, weight: .semibold),
- .foregroundColor: Theme.secondaryText,
- .strikethroughStyle: NSUnderlineStyle.single.rawValue
- ]
- let newAttributes: [NSAttributedString.Key: Any] = [
- .font: NSFont.systemFont(ofSize: 12, weight: .bold),
- .foregroundColor: Theme.successText
- ]
- full.append(NSAttributedString(string: "\(oldPrice) ", attributes: oldAttributes))
- full.append(NSAttributedString(string: newPrice, attributes: newAttributes))
- let label = NSTextField(labelWithAttributedString: full)
- return label
- }
- private func pillLabel(text: String, tint: NSColor, textColor: NSColor) -> NSTextField {
- let pill = NSTextField(labelWithString: text)
- pill.font = .systemFont(ofSize: 10, weight: .semibold)
- pill.textColor = textColor
- pill.alignment = .center
- pill.wantsLayer = true
- pill.layer?.backgroundColor = tint.cgColor
- pill.layer?.cornerRadius = 9
- pill.translatesAutoresizingMaskIntoConstraints = false
- pill.heightAnchor.constraint(equalToConstant: 18).isActive = true
- pill.widthAnchor.constraint(greaterThanOrEqualToConstant: 95).isActive = true
- return pill
- }
- private func makeTrustRow() -> NSView {
- let badges = NSStackView(views: [
- trustBadge(icon: "shield.fill", title: L("Secure Payments"), subtitle: L("Your payment is 100% secure.")),
- trustBadge(icon: "arrow.counterclockwise", title: L("Cancel Anytime"), subtitle: L("No commitment, cancel anytime.")),
- trustBadge(icon: "headphones", title: L("24/7 Support"), subtitle: L("We're here to help you anytime.")),
- trustBadge(icon: "lock.fill", title: L("Privacy First"), subtitle: L("Your data is safe with us."))
- ])
- badges.orientation = .horizontal
- badges.alignment = .centerY
- badges.distribution = .fillEqually
- badges.spacing = 12
- badges.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
- badges.translatesAutoresizingMaskIntoConstraints = false
- badges.wantsLayer = true
- badges.layer?.backgroundColor = Theme.bottomStrip.cgColor
- badges.layer?.borderColor = Theme.divider.cgColor
- badges.layer?.borderWidth = 1
- badges.layer?.cornerRadius = 10
- badges.setHuggingPriority(.defaultLow, for: .horizontal)
- badges.heightAnchor.constraint(equalToConstant: 72).isActive = true
- trustBadgesRow = badges
- return badges
- }
- private func makeFooterRow() -> NSView {
- footerLinkButtons = []
- let primary = footerActionCell(
- title: subscriptionPrimaryFooterTitle(),
- action: #selector(didTapPrimaryFooterSubscriptionAction),
- showsTrailingDivider: true
- )
- subscriptionPrimaryFooterButton = primary.button
- let entries: [(text: String, action: Selector)] = [
- (L("Restore Purchase"), #selector(didTapRestorePurchases)),
- (L("Privacy Policy"), #selector(didTapFooterPrivacyPolicy)),
- (L("Terms of Use"), #selector(didTapFooterTermsOfServices)),
- (L("Support"), #selector(didTapFooterSupport))
- ]
- let cells = [primary.container] + entries.enumerated().map { index, entry in
- footerActionCell(title: entry.text, action: entry.action, showsTrailingDivider: index < entries.count - 1).container
- }
- let links = NSStackView(views: cells)
- links.orientation = .horizontal
- links.distribution = .fillEqually
- links.spacing = 0
- links.alignment = .centerY
- links.translatesAutoresizingMaskIntoConstraints = false
- return links
- }
- private func footerActionCell(title: String, action: Selector, showsTrailingDivider: Bool) -> (container: NSView, button: NSButton) {
- let container = NSView()
- container.translatesAutoresizingMaskIntoConstraints = false
- let button = FooterLinkButton(title: title, target: self, action: action)
- button.isBordered = false
- button.bezelStyle = .rounded
- button.font = .systemFont(ofSize: 12, weight: .medium)
- button.contentTintColor = Theme.secondaryText
- button.focusRingType = .none
- button.translatesAutoresizingMaskIntoConstraints = false
- footerLinkButtons.append(button)
- container.addSubview(button)
- var constraints: [NSLayoutConstraint] = [
- button.centerXAnchor.constraint(equalTo: container.centerXAnchor),
- button.centerYAnchor.constraint(equalTo: container.centerYAnchor)
- ]
- if showsTrailingDivider {
- let divider = footerDivider()
- container.addSubview(divider)
- constraints.append(contentsOf: [
- divider.trailingAnchor.constraint(equalTo: container.trailingAnchor),
- divider.centerYAnchor.constraint(equalTo: container.centerYAnchor)
- ])
- }
- NSLayoutConstraint.activate(constraints)
- return (container, button)
- }
- private enum PrimaryFooterSubscriptionTitle {
- static var manage: String { L("Manage Subscription") }
- static var continueFree: String { L("Continue with free plan") }
- }
- private func subscriptionPrimaryFooterTitle() -> String {
- subscriptionStore.isProActive ? PrimaryFooterSubscriptionTitle.manage : PrimaryFooterSubscriptionTitle.continueFree
- }
- private func updateSubscriptionPrimaryFooter() {
- subscriptionPrimaryFooterButton?.title = subscriptionPrimaryFooterTitle()
- }
- private func trustBadge(icon: String, title: String, subtitle: String) -> NSView {
- let image = NSImageView()
- image.translatesAutoresizingMaskIntoConstraints = false
- image.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
- image.image = NSImage(systemSymbolName: icon, accessibilityDescription: nil)
- image.contentTintColor = Theme.primaryText
- let titleLabel = NSTextField(labelWithString: title)
- titleLabel.font = .systemFont(ofSize: 12, weight: .bold)
- titleLabel.textColor = Theme.primaryText
- let subtitleLabel = NSTextField(labelWithString: subtitle)
- subtitleLabel.font = .systemFont(ofSize: 10, weight: .medium)
- subtitleLabel.textColor = Theme.secondaryText
- let textStack = NSStackView(views: [titleLabel, subtitleLabel])
- textStack.orientation = .vertical
- textStack.spacing = 2
- textStack.alignment = .leading
- let stack = NSStackView(views: [image, textStack])
- stack.orientation = .horizontal
- stack.spacing = 8
- stack.alignment = .leading
- stack.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
- stack.wantsLayer = true
- stack.layer?.backgroundColor = NSColor.clear.cgColor
- return stack
- }
- private func footerDivider() -> NSBox {
- let divider = NSBox()
- divider.boxType = .separator
- divider.borderColor = Theme.divider
- divider.translatesAutoresizingMaskIntoConstraints = false
- divider.widthAnchor.constraint(equalToConstant: 1).isActive = true
- divider.heightAnchor.constraint(equalToConstant: 14).isActive = true
- return divider
- }
- @objc private func didTapSelectPlan(_ sender: NSButton) {
- guard let planKey = sender.identifier?.rawValue else { return }
- Task { await purchasePlan(planKey: planKey) }
- }
- @objc private func didTapPrimaryFooterSubscriptionAction(_ sender: NSButton) {
- let userTappedManage = (sender.title == PrimaryFooterSubscriptionTitle.manage)
- Task { @MainActor [weak self] in
- guard let self else { return }
- await subscriptionStore.refreshEntitlements(deep: true)
- updateSubscriptionPrimaryFooter()
- let active = subscriptionStore.isProActive
- if active || userTappedManage {
- guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else { return }
- NSWorkspace.shared.open(url)
- return
- }
- // Non-pro: dismiss paywall and return to the home (dashboard) window.
- dismissPremiumSheetFromParentIfNeeded()
- }
- }
- @objc private func didTapRestorePurchases() {
- Task { await restorePurchases() }
- }
- @objc private func didTapFooterPrivacyPolicy() {
- AppLegalURLs.openInSafari(AppLegalURLs.privacyPolicy)
- }
- @objc private func didTapFooterTermsOfServices() {
- AppLegalURLs.openInSafari(AppLegalURLs.termsOfUse)
- }
- @objc private func didTapFooterSupport() {
- AppLegalURLs.openInSafari(AppLegalURLs.support)
- }
- private func loadStoreProducts() async {
- applyStorePricing()
- await subscriptionStore.ensureProductsLoaded()
- applyStorePricing()
- updateSubscriptionPrimaryFooter()
- updatePremiumCloseButtonVisibility()
- await subscriptionStore.refreshEntitlements(deep: true)
- updateSubscriptionPrimaryFooter()
- updatePremiumCloseButtonVisibility()
- }
- private func applyStorePricing() {
- for plan in plans {
- guard let fields = planPriceFields[plan.id] else { continue }
- guard let product = subscriptionStore.product(forPlanKey: plan.id) else {
- fields.price.stringValue = Self.unloadedPricePlaceholder
- continue
- }
- fields.price.stringValue = product.displayPrice
- if let period = product.subscription?.subscriptionPeriod {
- fields.period.stringValue = periodSuffix(for: period)
- }
- }
- }
- private func periodSuffix(for period: Product.SubscriptionPeriod) -> String {
- let value = period.value
- switch period.unit {
- case .day: return value == 1 ? L("/ day") : String(format: L("/ %d days"), value)
- case .week: return value == 1 ? L("/ week") : String(format: L("/ %d weeks"), value)
- case .month: return value == 1 ? L("/ month") : String(format: L("/ %d months"), value)
- case .year: return value == 1 ? L("/ year") : String(format: L("/ %d years"), value)
- @unknown default: return ""
- }
- }
- private func setPurchasing(_ isPurchasing: Bool) {
- for button in planPurchaseButtons.values {
- button.isEnabled = !isPurchasing
- }
- }
- private func purchasePlan(planKey: String) async {
- setPurchasing(true)
- defer { setPurchasing(false) }
- do {
- let completed = try await subscriptionStore.purchase(planKey: planKey)
- guard completed else { return }
- AppRatingCoordinator.shared.scheduleReviewAfterSubscriptionPurchase()
- let alert = NSAlert()
- alert.messageText = L("You're subscribed")
- alert.informativeText = L("Thank you — Pro features are now available.")
- alert.alertStyle = .informational
- alert.addButton(withTitle: L("OK"))
- if let window = view.window {
- alert.beginSheetModal(for: window) { [weak self] _ in
- self?.dismissPremiumSheetFromParentIfNeeded()
- }
- } else {
- alert.runModal()
- dismissPremiumSheetFromParentIfNeeded()
- }
- } catch {
- await MainActor.run {
- self.presentPurchaseError(error)
- }
- }
- }
- private func restorePurchases() async {
- setPurchasing(true)
- defer { setPurchasing(false) }
- do {
- try await subscriptionStore.restorePurchases()
- let active = subscriptionStore.isProActive
- let alert = NSAlert()
- if active {
- alert.messageText = L("Purchases restored")
- alert.informativeText = L("Your subscription is active.")
- } else {
- alert.messageText = L("No subscription found")
- alert.informativeText = L("There was nothing to restore for this Apple ID.")
- }
- alert.alertStyle = .informational
- alert.addButton(withTitle: L("OK"))
- if let window = view.window {
- alert.beginSheetModal(for: window) { [weak self] _ in
- if active {
- self?.dismissPremiumSheetFromParentIfNeeded()
- }
- }
- } else {
- alert.runModal()
- if active {
- dismissPremiumSheetFromParentIfNeeded()
- }
- }
- } catch {
- await MainActor.run {
- self.presentPurchaseError(error)
- }
- }
- }
- private func presentPurchaseError(_ error: Error) {
- let alert = NSAlert()
- alert.messageText = L("Something went wrong")
- if let localized = error as? LocalizedError {
- var parts: [String] = []
- if let description = localized.errorDescription {
- parts.append(description)
- }
- if let recovery = localized.recoverySuggestion {
- parts.append(recovery)
- }
- alert.informativeText = parts.isEmpty ? error.localizedDescription : parts.joined(separator: "\n\n")
- } else {
- alert.informativeText = error.localizedDescription
- }
- alert.alertStyle = .warning
- alert.addButton(withTitle: L("OK"))
- if let window = view.window {
- alert.beginSheetModal(for: window)
- } else {
- alert.runModal()
- }
- }
- private func applyLocalizedStrings() {
- view.window?.title = L("Premium Plans")
- premiumTitleLabel?.stringValue = L("Upgrade to Pro")
- premiumSubtitleLabel?.stringValue = L("Unlock unlimited access to premium tools and boost your productivity.")
- for target in pricingCardTargets {
- guard let plan = plans.first(where: { $0.id == target.planId }) else { continue }
- target.titleLabel.stringValue = plan.title
- target.subtitleLabel.stringValue = plan.subtitle
- if subscriptionStore.product(forPlanKey: plan.id) == nil {
- target.periodLabel.stringValue = plan.period
- }
- target.billedPillLabel?.stringValue = plan.billedPill
- target.billedPillLabel?.isHidden = plan.billedPill.isEmpty
- for (index, label) in target.featureLabels.enumerated() where index < plan.features.count {
- label.stringValue = plan.features[index]
- }
- target.purchaseButton.title = String(format: L("Get %@"), plan.title)
- }
- if let trustBadgesRow {
- let trustData: [(String, String)] = [
- (L("Secure Payments"), L("Your payment is 100% secure.")),
- (L("Cancel Anytime"), L("No commitment, cancel anytime.")),
- (L("24/7 Support"), L("We're here to help you anytime.")),
- (L("Privacy First"), L("Your data is safe with us."))
- ]
- for (index, subview) in trustBadgesRow.arrangedSubviews.enumerated() {
- guard let badge = subview as? NSStackView, index < trustData.count else { continue }
- for case let textStack as NSStackView in badge.arrangedSubviews {
- let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
- if labels.count >= 2 {
- labels[0].stringValue = trustData[index].0
- labels[1].stringValue = trustData[index].1
- }
- }
- }
- }
- let footerTitles = [
- subscriptionPrimaryFooterTitle(),
- L("Restore Purchase"),
- L("Privacy Policy"),
- L("Terms of Use"),
- L("Support")
- ]
- for (index, button) in footerLinkButtons.enumerated() where index < footerTitles.count {
- button.title = footerTitles[index]
- }
- updateSubscriptionPrimaryFooter()
- applyStorePricing()
- }
- private func dismissPremiumSheetFromParentIfNeeded() {
- guard let sheet = view.window, let parent = sheet.sheetParent else { return }
- parent.endSheet(sheet)
- }
- @objc private func didTapClose() {
- guard let window = view.window else { return }
- if let parent = window.sheetParent {
- parent.endSheet(window)
- return
- }
- window.close()
- }
- private func applyCurrentAppearance() {
- view.window?.backgroundColor = PremiumPlansWindowController.paywallSheetBackground
- pageGradient.colors = [Theme.pageStart.cgColor, Theme.pageEnd.cgColor]
- premiumTitleLabel?.textColor = Theme.primaryText
- premiumSubtitleLabel?.textColor = Theme.secondaryText
- for target in pricingCardTargets {
- target.card.updateBorderColors(base: Theme.cardBorder, hover: Theme.accent)
- target.card.layer?.backgroundColor = Theme.cardBackground.cgColor
- target.iconWell.layer?.backgroundColor = Theme.bottomStrip.cgColor
- target.planIconView.contentTintColor = planIconTint(planId: target.planId)
- target.titleLabel.textColor = Theme.primaryText
- target.subtitleLabel.textColor = Theme.secondaryText
- target.priceLabel.textColor = Theme.primaryText
- target.periodLabel.textColor = Theme.secondaryText
- target.billingLabel?.textColor = Theme.secondaryText
- target.divider.borderColor = Theme.divider
- for label in target.featureLabels {
- label.textColor = Theme.primaryText
- }
- for icon in target.featureIcons {
- icon.contentTintColor = Theme.iconTint
- }
- target.purchaseButton.refreshAppearance()
- }
- if let trustBadgesRow {
- trustBadgesRow.layer?.backgroundColor = Theme.bottomStrip.cgColor
- trustBadgesRow.layer?.borderColor = Theme.divider.cgColor
- for case let badge as NSStackView in trustBadgesRow.arrangedSubviews {
- for case let image as NSImageView in badge.arrangedSubviews {
- image.contentTintColor = Theme.primaryText
- }
- for case let textStack as NSStackView in badge.arrangedSubviews {
- let labels = textStack.arrangedSubviews.compactMap { $0 as? NSTextField }
- if labels.count >= 2 {
- labels[0].textColor = Theme.primaryText
- labels[1].textColor = Theme.secondaryText
- }
- }
- }
- }
- for button in footerLinkButtons {
- button.contentTintColor = Theme.secondaryText
- }
- premiumCloseButton?.refreshAppearance(hovered: false)
- }
- private func planIconTint(planId: String) -> NSColor {
- switch planId {
- case "monthly": Theme.accent
- case "yearly": Theme.successText
- default: Theme.iconTint
- }
- }
- }
|