| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973 |
- import Cocoa
- import StoreKit
- // MARK: - Plan Model
- enum PaywallPlan: CaseIterable {
- case monthly
- case yearly
- case lifetime
- var productID: String {
- switch self {
- case .monthly: StoreProductID.monthly
- case .yearly: StoreProductID.yearly
- case .lifetime: StoreProductID.lifetime
- }
- }
- func planCopy(from config: PaywallConfig) -> PaywallConfig.PlanCopy {
- switch self {
- case .monthly: config.plans.monthly
- case .yearly: config.plans.yearly
- case .lifetime: config.plans.lifetime
- }
- }
- func localizedPrice(from product: Product?, config: PaywallConfig) -> String {
- product?.displayPrice ?? config.loadingPrice
- }
- func localizedSubtitle(
- from product: Product?,
- config: PaywallConfig,
- introOffer: Product.SubscriptionOffer? = nil
- ) -> String {
- guard let product else { return config.loadingPrice }
- let copy = planCopy(from: config)
- let price = product.displayPrice
- if self == .yearly, let introOffer, let trialTemplate = copy.trialSubtitleTemplate {
- let duration = config.trialDurationDescription(from: introOffer, lowercase: true)
- return trialTemplate
- .replacingOccurrences(of: "{trial}", with: duration)
- .replacingOccurrences(of: "{price}", with: price)
- }
- return copy.subtitleTemplate.replacingOccurrences(of: "{price}", with: price)
- }
- func localizedCTATitle(
- from product: Product?,
- config: PaywallConfig,
- introOffer: Product.SubscriptionOffer? = nil
- ) -> String {
- guard let product else { return config.loadingCTA }
- let copy = planCopy(from: config)
- let price = product.displayPrice
- if self == .yearly, let introOffer {
- return config.trialCTATitle(from: introOffer)
- }
- return copy.ctaTemplate.replacingOccurrences(of: "{price}", with: price)
- }
- func localizedRenewalDisclosure(
- from product: Product?,
- config: PaywallConfig,
- introOffer: Product.SubscriptionOffer? = nil
- ) -> String {
- switch self {
- case .lifetime:
- return config.lifetimeDisclosure
- case .monthly, .yearly:
- guard let product else { return config.loadingDisclosure }
- let price = product.displayPrice
- let period = product.subscription.map {
- config.subscriptionPeriodDescription(from: $0.subscriptionPeriod)
- } ?? config.messages.periodFallback
- if self == .yearly, let introOffer {
- let trial = config.trialDurationDescription(from: introOffer, lowercase: true)
- return config.trialDisclosureTemplate
- .replacingOccurrences(of: "{trial}", with: trial)
- .replacingOccurrences(of: "{price}", with: price)
- .replacingOccurrences(of: "{period}", with: period)
- }
- return config.subscriptionDisclosureTemplate
- .replacingOccurrences(of: "{price}", with: price)
- .replacingOccurrences(of: "{period}", with: period)
- }
- }
- }
- // MARK: - StoreKit
- enum StoreProductID {
- static let monthly = AppStoreConfig.ProductID.monthly
- static let yearly = AppStoreConfig.ProductID.yearly
- static let lifetime = AppStoreConfig.ProductID.lifetime
- static let all = AppStoreConfig.ProductID.all
- }
- enum PremiumAccessKind: String {
- case none
- case subscription
- case lifetime
- }
- enum StoreError: Error {
- case productNotFound
- case failedVerification
- }
- enum PurchaseOutcome: Sendable {
- case purchased
- case cancelled
- case pending
- }
- @MainActor
- final class StoreManager {
- static let shared = StoreManager()
- private static let cachedPremiumKey = "StoreManager.cachedIsPremium"
- private static let cachedPremiumKindKey = "StoreManager.cachedPremiumAccessKind"
- private(set) var products: [Product] = []
- private(set) var isPremium = UserDefaults.standard.bool(forKey: cachedPremiumKey)
- private(set) var premiumAccessKind: PremiumAccessKind = {
- guard let raw = UserDefaults.standard.string(forKey: cachedPremiumKindKey),
- let kind = PremiumAccessKind(rawValue: raw) else {
- return .none
- }
- return kind
- }()
- var isPro: Bool { isPremium }
- var hasActiveSubscription: Bool { premiumAccessKind == .subscription }
- var hasLifetimeAccess: Bool { premiumAccessKind == .lifetime }
- private(set) var isLoadingProducts = false
- private(set) var productLoadError: String?
- private(set) var isPurchasing = false
- private(set) var isResolvingEntitlements = true
- private(set) var introOfferEligibleByProductID: [String: Bool] = [:]
- private var transactionListener: Task<Void, Never>?
- private var initialEntitlementTask: Task<Void, Never>?
- private var hasStarted = false
- private init() {}
- func start() {
- guard !hasStarted else { return }
- hasStarted = true
- transactionListener = Task { [weak self] in
- for await update in Transaction.updates {
- await self?.handleTransactionUpdate(update)
- }
- }
- initialEntitlementTask = Task { [weak self] in
- guard let self else { return }
- await self.refreshEntitlementsOnly()
- self.isResolvingEntitlements = false
- NotificationCenter.default.post(name: .entitlementsDidResolve, object: nil)
- await self.loadProducts()
- await self.refreshPremiumStatus()
- }
- }
- func ensureEntitlementsResolved() async {
- await initialEntitlementTask?.value
- }
- func product(for plan: PaywallPlan) -> Product? {
- products.first { $0.id == plan.productID }
- }
- func eligibleIntroOffer(for plan: PaywallPlan) -> Product.SubscriptionOffer? {
- guard let product = product(for: plan) else { return nil }
- return eligibleIntroOffer(for: product)
- }
- func eligibleIntroOffer(for product: Product) -> Product.SubscriptionOffer? {
- guard introOfferEligibleByProductID[product.id] == true,
- let offer = product.subscription?.introductoryOffer,
- offer.paymentMode == .freeTrial else {
- return nil
- }
- return offer
- }
- func loadProducts() async {
- isLoadingProducts = true
- productLoadError = nil
- postStoreStateDidChange()
- defer {
- isLoadingProducts = false
- postStoreStateDidChange()
- }
- do {
- let loaded = try await Product.products(for: StoreProductID.all)
- guard !loaded.isEmpty else {
- productLoadError = PaywallConfigService.shared.config.messages.noPlansAvailable
- products = []
- return
- }
- products = loaded.sorted { lhs, rhs in
- productSortOrder(for: lhs.id) < productSortOrder(for: rhs.id)
- }
- productLoadError = nil
- await refreshIntroOfferEligibility()
- NotificationCenter.default.post(name: .storeProductsDidUpdate, object: nil)
- } catch {
- productLoadError = PaywallConfigService.shared.config.messages.plansLoadFailed
- NSLog("Failed to load products: \(error.localizedDescription)")
- }
- }
- @discardableResult
- func purchase(plan: PaywallPlan) async throws -> PurchaseOutcome {
- if products.isEmpty {
- await loadProducts()
- }
- guard let product = product(for: plan) else {
- throw StoreError.productNotFound
- }
- isPurchasing = true
- postStoreStateDidChange()
- defer {
- isPurchasing = false
- postStoreStateDidChange()
- }
- let result = try await product.purchase()
- switch result {
- case .success(let verification):
- let transaction = try checkVerified(verification)
- await transaction.finish()
- await refreshPremiumStatus()
- return isPremium ? .purchased : .cancelled
- case .userCancelled:
- return .cancelled
- case .pending:
- return .pending
- @unknown default:
- return .cancelled
- }
- }
- @discardableResult
- func restorePurchases() async throws -> Bool {
- isPurchasing = true
- postStoreStateDidChange()
- defer {
- isPurchasing = false
- postStoreStateDidChange()
- }
- try await AppStore.sync()
- await refreshPremiumStatus()
- return isPremium
- }
- func showAlert(title: String, message: String, on window: NSWindow?) {
- let alert = NSAlert()
- alert.messageText = title
- alert.informativeText = message
- alert.alertStyle = .informational
- alert.addButton(withTitle: PaywallConfigService.shared.config.messages.alertOK)
- if let window {
- alert.beginSheetModal(for: window)
- } else {
- alert.runModal()
- }
- }
- func showManageSubscriptions() {
- let urlString = PaywallConfigService.shared.config.urls.manageSubscriptions
- guard let url = URL(string: urlString) else { return }
- NSWorkspace.shared.open(url)
- }
- func showPurchaseError(_ error: Error, on window: NSWindow?) {
- let messages = PaywallConfigService.shared.config.messages
- switch error {
- case StoreError.productNotFound:
- showAlert(title: messages.purchaseFailedTitle, message: messages.productNotFound, on: window)
- case StoreError.failedVerification:
- showAlert(title: messages.purchaseFailedTitle, message: messages.failedVerification, on: window)
- default:
- if let storeKitError = error as? StoreKitError, case .userCancelled = storeKitError {
- return
- }
- showAlert(title: messages.purchaseFailedTitle, message: error.localizedDescription, on: window)
- }
- }
- private func handleTransactionUpdate(_ update: VerificationResult<Transaction>) async {
- do {
- let transaction = try checkVerified(update)
- await transaction.finish()
- await refreshPremiumStatus()
- } catch {
- NSLog("Transaction verification failed: \(error.localizedDescription)")
- }
- }
- func refreshEntitlementsOnly() async {
- applyPremiumStatus(await resolvePremiumAccessKind())
- }
- func refreshPremiumStatus() async {
- await refreshIntroOfferEligibility()
- applyPremiumStatus(await resolvePremiumAccessKind())
- }
- private func applyPremiumStatus(_ kind: PremiumAccessKind) {
- let hasPremium = kind != .none
- let didChange = hasPremium != isPremium || kind != premiumAccessKind
- isPremium = hasPremium
- premiumAccessKind = hasPremium ? kind : .none
- UserDefaults.standard.set(hasPremium, forKey: Self.cachedPremiumKey)
- UserDefaults.standard.set(premiumAccessKind.rawValue, forKey: Self.cachedPremiumKindKey)
- if didChange {
- NotificationCenter.default.post(name: .premiumStatusDidChange, object: nil)
- }
- postStoreStateDidChange()
- }
- private func resolvePremiumAccessKind() async -> PremiumAccessKind {
- if await hasActiveEntitlement(for: StoreProductID.lifetime) {
- return .lifetime
- }
- if await hasActiveEntitlement(for: StoreProductID.monthly) {
- return .subscription
- }
- if await hasActiveEntitlement(for: StoreProductID.yearly) {
- return .subscription
- }
- if await hasEntitlementFromSubscriptionStatus() {
- return .subscription
- }
- return .none
- }
- private func hasActiveEntitlement(for productID: String) async -> Bool {
- for await result in Transaction.currentEntitlements {
- guard let transaction = try? checkVerified(result) else { continue }
- if transaction.productID == productID, isActivePremiumTransaction(transaction) {
- return true
- }
- }
- guard let result = await Transaction.latest(for: productID),
- let transaction = try? checkVerified(result) else {
- return false
- }
- return isActivePremiumTransaction(transaction)
- }
- private func hasEntitlementFromSubscriptionStatus() async -> Bool {
- for product in products where product.subscription != nil {
- guard StoreProductID.all.contains(product.id) else { continue }
- guard let statuses = try? await product.subscription?.status else { continue }
- for status in statuses {
- switch status.state {
- case .subscribed, .inGracePeriod, .inBillingRetryPeriod:
- return true
- default:
- continue
- }
- }
- }
- return false
- }
- private func isActivePremiumTransaction(_ transaction: Transaction) -> Bool {
- guard StoreProductID.all.contains(transaction.productID) else { return false }
- guard transaction.revocationDate == nil else { return false }
- if let expirationDate = transaction.expirationDate {
- return expirationDate > Date()
- }
- return true
- }
- private func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {
- switch result {
- case .unverified:
- throw StoreError.failedVerification
- case .verified(let safe):
- return safe
- }
- }
- private func productSortOrder(for productID: String) -> Int {
- switch productID {
- case StoreProductID.monthly: 0
- case StoreProductID.yearly: 1
- case StoreProductID.lifetime: 2
- default: 99
- }
- }
- private func refreshIntroOfferEligibility() async {
- var eligibility: [String: Bool] = [:]
- for product in products {
- guard let subscription = product.subscription,
- subscription.introductoryOffer != nil else {
- continue
- }
- let groupID = subscription.subscriptionGroupID
- eligibility[product.id] = await Product.SubscriptionInfo.isEligibleForIntroOffer(for: groupID)
- }
- introOfferEligibleByProductID = eligibility
- }
- private func postStoreStateDidChange() {
- NotificationCenter.default.post(name: .storeStateDidChange, object: nil)
- }
- }
- extension Notification.Name {
- static let premiumStatusDidChange = Notification.Name("premiumStatusDidChange")
- static let entitlementsDidResolve = Notification.Name("entitlementsDidResolve")
- static let storeProductsDidUpdate = Notification.Name("storeProductsDidUpdate")
- static let storeStateDidChange = Notification.Name("storeStateDidChange")
- }
- // MARK: - Premium Access
- enum PremiumAccess {
- @MainActor
- static func canAccess(_ feature: AppFeature) -> Bool {
- let store = StoreManager.shared
- guard !store.isResolvingEntitlements else { return false }
- return FreeTierManager.canAccess(feature, isPremium: store.isPremium)
- }
- @MainActor
- @discardableResult
- static func require(
- feature: AppFeature,
- from window: NSWindow?,
- returnToHomeOnDismiss: Bool = false
- ) -> Bool {
- guard canAccess(feature) else {
- presentPaywallOrLimitAlert(for: feature, from: window, returnToHomeOnDismiss: returnToHomeOnDismiss)
- return false
- }
- return true
- }
- @MainActor
- @discardableResult
- static func require(from window: NSWindow?, returnToHomeOnDismiss: Bool = false) -> Bool {
- require(feature: .documentImport, from: window, returnToHomeOnDismiss: returnToHomeOnDismiss)
- }
- @MainActor
- private static func presentPaywallOrLimitAlert(
- for feature: AppFeature,
- from window: NSWindow?,
- returnToHomeOnDismiss: Bool
- ) {
- if StoreManager.shared.isResolvingEntitlements {
- Task { @MainActor in
- await StoreManager.shared.ensureEntitlementsResolved()
- guard !canAccess(feature) else { return }
- presentPaywallOrLimitAlert(for: feature, from: window, returnToHomeOnDismiss: returnToHomeOnDismiss)
- }
- return
- }
- guard let viewController = mainViewController(from: window) else { return }
- viewController.presentPaywall(returnToHomeOnDismiss: returnToHomeOnDismiss)
- }
- @MainActor
- static func mainViewController(from window: NSWindow?) -> ViewController? {
- if let viewController = window?.contentViewController as? ViewController {
- return viewController
- }
- if let viewController = NSApp.keyWindow?.contentViewController as? ViewController {
- return viewController
- }
- for appWindow in NSApp.windows where appWindow.canBecomeMain {
- if let viewController = appWindow.contentViewController as? ViewController {
- return viewController
- }
- }
- return nil
- }
- }
- // MARK: - Left Panel
- private final class PaywallLeftPanelView: NSView, AppearanceRefreshable {
- private let gradientLayer = CAGradientLayer()
- override init(frame frameRect: NSRect) {
- super.init(frame: frameRect)
- wantsLayer = true
- gradientLayer.startPoint = CGPoint(x: 0.5, y: 1)
- gradientLayer.endPoint = CGPoint(x: 0.5, y: 0)
- layer?.insertSublayer(gradientLayer, at: 0)
- refreshAppearance()
- }
- func refreshAppearance() {
- gradientLayer.colors = AppTheme.paywallLeftGradientColors.map(\.cgColor)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- override func layout() {
- super.layout()
- gradientLayer.frame = bounds
- let mask = CAShapeLayer()
- mask.path = CGPath(
- roundedRect: bounds,
- cornerWidth: 20,
- cornerHeight: 20,
- transform: nil
- )
- layer?.mask = mask
- }
- }
- // MARK: - Badge
- private final class PaywallBadgeView: NSView {
- private let label: NSTextField
- init(text: String, iconName: String, background: NSColor, foreground: NSColor) {
- label = NSTextField(labelWithString: text)
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- wantsLayer = true
- layer?.backgroundColor = background.cgColor
- layer?.cornerRadius = 10
- layer?.masksToBounds = true
- let icon = NSImageView()
- icon.translatesAutoresizingMaskIntoConstraints = false
- if let image = NSImage(systemSymbolName: iconName, accessibilityDescription: nil) {
- let config = NSImage.SymbolConfiguration(pointSize: 9, weight: .semibold)
- icon.image = image.withSymbolConfiguration(config)
- }
- icon.contentTintColor = foreground
- label.font = AppTheme.semiboldFont(size: 10)
- label.textColor = foreground
- label.translatesAutoresizingMaskIntoConstraints = false
- addSubview(icon)
- addSubview(label)
- NSLayoutConstraint.activate([
- heightAnchor.constraint(equalToConstant: 20),
- icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
- icon.centerYAnchor.constraint(equalTo: centerYAnchor),
- icon.widthAnchor.constraint(equalToConstant: 12),
- icon.heightAnchor.constraint(equalToConstant: 12),
- label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 4),
- label.centerYAnchor.constraint(equalTo: centerYAnchor),
- label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
- ])
- }
- func updateText(_ text: String) {
- label.stringValue = text
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- }
- // MARK: - Feature Row
- private final class PaywallFeatureRow: NSView, AppearanceRefreshable {
- private let label: NSTextField
- init(text: String) {
- label = NSTextField.themeLabel(text, style: .primary, font: AppTheme.regularFont(size: 14))
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- let checkContainer = NSView()
- checkContainer.translatesAutoresizingMaskIntoConstraints = false
- checkContainer.wantsLayer = true
- checkContainer.layer?.backgroundColor = AppTheme.green.cgColor
- checkContainer.layer?.cornerRadius = 10
- checkContainer.layer?.masksToBounds = true
- let checkIcon = NSImageView()
- checkIcon.translatesAutoresizingMaskIntoConstraints = false
- if let image = NSImage(systemSymbolName: "checkmark", accessibilityDescription: nil) {
- let config = NSImage.SymbolConfiguration(pointSize: 9, weight: .bold)
- checkIcon.image = image.withSymbolConfiguration(config)
- }
- checkIcon.contentTintColor = .white
- label.translatesAutoresizingMaskIntoConstraints = false
- addSubview(checkContainer)
- checkContainer.addSubview(checkIcon)
- addSubview(label)
- NSLayoutConstraint.activate([
- heightAnchor.constraint(equalToConstant: 28),
- checkContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
- checkContainer.centerYAnchor.constraint(equalTo: centerYAnchor),
- checkContainer.widthAnchor.constraint(equalToConstant: 20),
- checkContainer.heightAnchor.constraint(equalToConstant: 20),
- checkIcon.centerXAnchor.constraint(equalTo: checkContainer.centerXAnchor),
- checkIcon.centerYAnchor.constraint(equalTo: checkContainer.centerYAnchor),
- checkIcon.widthAnchor.constraint(equalToConstant: 12),
- checkIcon.heightAnchor.constraint(equalToConstant: 12),
- label.leadingAnchor.constraint(equalTo: checkContainer.trailingAnchor, constant: 12),
- label.centerYAnchor.constraint(equalTo: centerYAnchor),
- label.trailingAnchor.constraint(equalTo: trailingAnchor),
- ])
- }
- func updateText(_ text: String) {
- label.stringValue = text
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func refreshAppearance() {
- label.refreshThemeLabelColor()
- }
- }
- // MARK: - Plan Card
- private final class PaywallPlanCard: NSControl, AppearanceRefreshable {
- var onSelect: (() -> Void)?
- private let plan: PaywallPlan
- private let titleLabel = NSTextField(labelWithString: "")
- private let subtitleLabel = NSTextField(labelWithString: "")
- private let priceLabel = NSTextField(labelWithString: "")
- private var badgeView: PaywallBadgeView?
- private var trialBadgeView: PaywallBadgeView?
- private var hoverTracker: HoverTracker?
- private var isHovered = false
- var isChosen: Bool = false {
- didSet { updateAppearance() }
- }
- init(plan: PaywallPlan) {
- self.plan = plan
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- wantsLayer = true
- layer?.cornerRadius = 12
- layer?.masksToBounds = false
- let config = PaywallConfigService.shared.config
- titleLabel.stringValue = plan.planCopy(from: config).title
- titleLabel.font = AppTheme.semiboldFont(size: 15)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- subtitleLabel.stringValue = config.loadingPrice
- subtitleLabel.font = AppTheme.regularFont(size: 11)
- subtitleLabel.themeLabelStyle = .secondary
- subtitleLabel.textColor = AppTheme.textSecondary
- subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
- priceLabel.stringValue = config.loadingPrice
- priceLabel.font = AppTheme.semiboldFont(size: 15)
- priceLabel.alignment = .right
- priceLabel.translatesAutoresizingMaskIntoConstraints = false
- addSubview(titleLabel)
- addSubview(subtitleLabel)
- addSubview(priceLabel)
- NSLayoutConstraint.activate([
- heightAnchor.constraint(equalToConstant: 86),
- titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
- titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 24),
- subtitleLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 3),
- subtitleLabel.trailingAnchor.constraint(lessThanOrEqualTo: priceLabel.leadingAnchor, constant: -12),
- priceLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
- priceLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
- ])
- if plan == .lifetime, let badgeText = plan.planCopy(from: config).badge {
- let badge = PaywallBadgeView(
- text: badgeText,
- iconName: "star.fill",
- background: AppTheme.paywallGold,
- foreground: AppTheme.paywallGoldText
- )
- badgeView = badge
- addSubview(badge)
- NSLayoutConstraint.activate([
- badge.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),
- badge.topAnchor.constraint(equalTo: topAnchor, constant: 8),
- ])
- }
- applyCardShadow()
- updateAppearance()
- hoverTracker = HoverTracker(view: self) { [weak self] hovering in
- self?.setHovered(hovering)
- }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func updateDisplay(
- product: Product?,
- config: PaywallConfig,
- introOffer: Product.SubscriptionOffer? = nil
- ) {
- titleLabel.stringValue = plan.planCopy(from: config).title
- subtitleLabel.stringValue = plan.localizedSubtitle(from: product, config: config, introOffer: introOffer)
- priceLabel.stringValue = plan.localizedPrice(from: product, config: config)
- updateLifetimeBadge(config: config)
- updateTrialBadge(introOffer: introOffer)
- }
- private func updateLifetimeBadge(config: PaywallConfig) {
- guard plan == .lifetime else { return }
- if let badgeText = plan.planCopy(from: config).badge {
- if let badgeView {
- badgeView.updateText(badgeText)
- badgeView.isHidden = false
- }
- } else {
- badgeView?.isHidden = true
- }
- }
- private func updateTrialBadge(introOffer: Product.SubscriptionOffer?) {
- guard plan == .yearly else { return }
- if let introOffer {
- let text = PaywallConfigService.shared.config.trialBadgeText(from: introOffer)
- if let trialBadgeView {
- trialBadgeView.updateText(text)
- trialBadgeView.isHidden = false
- } else {
- let badge = PaywallBadgeView(
- text: text,
- iconName: "calendar",
- background: AppTheme.paywallPink,
- foreground: AppTheme.paywallPinkText
- )
- trialBadgeView = badge
- addSubview(badge)
- NSLayoutConstraint.activate([
- badge.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),
- badge.topAnchor.constraint(equalTo: topAnchor, constant: 8),
- ])
- }
- } else {
- trialBadgeView?.isHidden = true
- }
- }
- func refreshAppearance() {
- updateAppearance()
- subtitleLabel.refreshThemeLabelColor()
- if isHovered {
- applyHoverLift(true)
- }
- }
- private func setHovered(_ hovering: Bool) {
- isHovered = hovering
- applyHoverLift(hovering)
- updateAppearance()
- }
- private func updateAppearance() {
- let titleColor = isChosen && plan == .yearly ? AppTheme.green : AppTheme.paywallAccent
- titleLabel.textColor = titleColor
- priceLabel.textColor = titleColor
- layer?.backgroundColor = AppTheme.paywallTrustBackground.cgColor
- if isChosen {
- layer?.borderWidth = 2
- layer?.borderColor = AppTheme.green.cgColor
- } else if isHovered {
- layer?.borderWidth = 2
- let hoverBorder = AppTheme.paywallBorder.blended(withFraction: 0.35, of: AppTheme.paywallAccent)
- ?? AppTheme.paywallBorder
- layer?.borderColor = hoverBorder.cgColor
- } else {
- layer?.borderWidth = 1.5
- layer?.borderColor = AppTheme.paywallBorder.cgColor
- }
- }
- override func mouseUp(with event: NSEvent) {
- guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
- onSelect?()
- }
- override func resetCursorRects() {
- addCursorRect(bounds, cursor: .pointingHand)
- }
- }
- // MARK: - Footer Link
- private final class PaywallFooterLink: NSButton, AppearanceRefreshable {
- private var hoverTracker: HoverTracker?
- private var isHovered = false
- init(title: String) {
- super.init(frame: .zero)
- updateTitle(title)
- isBordered = false
- bezelStyle = .inline
- font = AppTheme.regularFont(size: 11)
- translatesAutoresizingMaskIntoConstraints = false
- refreshAppearance()
- hoverTracker = HoverTracker(view: self) { [weak self] hovering in
- self?.isHovered = hovering
- self?.refreshAppearance()
- }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func updateTitle(_ title: String) {
- self.title = title
- invalidateIntrinsicContentSize()
- needsDisplay = true
- }
- func refreshAppearance() {
- contentTintColor = isHovered ? AppTheme.textPrimary : AppTheme.textSecondary
- }
- override func resetCursorRects() {
- addCursorRect(bounds, cursor: .pointingHand)
- }
- }
- // MARK: - Footer Trust Item
- private final class PaywallTrustItemView: NSView, AppearanceRefreshable {
- private let iconContainer = NSView()
- private let icon = NSImageView()
- private let titleLabel: NSTextField
- private let subtitleLabel: NSTextField
- init(iconName: String, title: String, subtitle: String) {
- titleLabel = NSTextField.themeLabel(title, style: .primary, font: AppTheme.semiboldFont(size: 11))
- subtitleLabel = NSTextField.themeLabel(subtitle, style: .secondary, font: AppTheme.regularFont(size: 9))
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- iconContainer.translatesAutoresizingMaskIntoConstraints = false
- iconContainer.wantsLayer = true
- iconContainer.layer?.cornerRadius = 10
- iconContainer.layer?.masksToBounds = true
- icon.translatesAutoresizingMaskIntoConstraints = false
- if let image = NSImage(systemSymbolName: iconName, accessibilityDescription: nil) {
- let config = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
- icon.image = image.withSymbolConfiguration(config)
- }
- titleLabel.lineBreakMode = .byTruncatingTail
- titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- subtitleLabel.lineBreakMode = .byTruncatingTail
- subtitleLabel.maximumNumberOfLines = 2
- subtitleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
- addSubview(iconContainer)
- iconContainer.addSubview(icon)
- addSubview(titleLabel)
- addSubview(subtitleLabel)
- NSLayoutConstraint.activate([
- heightAnchor.constraint(equalToConstant: Self.preferredHeight),
- iconContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
- iconContainer.topAnchor.constraint(equalTo: topAnchor),
- iconContainer.widthAnchor.constraint(equalToConstant: 20),
- iconContainer.heightAnchor.constraint(equalToConstant: 20),
- icon.centerXAnchor.constraint(equalTo: iconContainer.centerXAnchor),
- icon.centerYAnchor.constraint(equalTo: iconContainer.centerYAnchor),
- icon.widthAnchor.constraint(equalToConstant: 12),
- icon.heightAnchor.constraint(equalToConstant: 12),
- titleLabel.leadingAnchor.constraint(equalTo: iconContainer.trailingAnchor, constant: 8),
- titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 1),
- titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
- subtitleLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
- subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
- subtitleLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
- ])
- setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- setContentHuggingPriority(.defaultLow, for: .horizontal)
- setContentHuggingPriority(.required, for: .vertical)
- setContentCompressionResistancePriority(.required, for: .vertical)
- refreshAppearance()
- }
- fileprivate static let preferredHeight: CGFloat = 34
- func update(iconName: String, title: String, subtitle: String) {
- titleLabel.stringValue = title
- subtitleLabel.stringValue = subtitle
- if let image = NSImage(systemSymbolName: iconName, accessibilityDescription: nil) {
- let symbolConfig = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
- icon.image = image.withSymbolConfiguration(symbolConfig)
- }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func refreshAppearance() {
- iconContainer.layer?.backgroundColor = AppTheme.paywallTrustIconBackground.cgColor
- icon.contentTintColor = AppTheme.paywallIconAccent
- titleLabel.refreshThemeLabelColor()
- subtitleLabel.refreshThemeLabelColor()
- }
- }
- // MARK: - Products Error
- private final class PaywallProductsErrorView: NSView, AppearanceRefreshable {
- var onRetry: (() -> Void)?
- private let messageLabel = NSTextField(wrappingLabelWithString: "")
- private let retryButton = PaywallFooterLink(title: "")
- init() {
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- messageLabel.font = AppTheme.regularFont(size: 12)
- messageLabel.textColor = AppTheme.textSecondary
- messageLabel.alignment = .center
- messageLabel.maximumNumberOfLines = 3
- messageLabel.lineBreakMode = .byWordWrapping
- messageLabel.cell?.wraps = true
- messageLabel.cell?.isScrollable = false
- messageLabel.translatesAutoresizingMaskIntoConstraints = false
- retryButton.target = self
- retryButton.action = #selector(retryTapped)
- addSubview(messageLabel)
- addSubview(retryButton)
- NSLayoutConstraint.activate([
- messageLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
- messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
- messageLabel.topAnchor.constraint(equalTo: topAnchor),
- retryButton.centerXAnchor.constraint(equalTo: centerXAnchor),
- retryButton.topAnchor.constraint(equalTo: messageLabel.bottomAnchor, constant: 8),
- retryButton.bottomAnchor.constraint(equalTo: bottomAnchor),
- ])
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func update(message: String, isRetrying: Bool) {
- let messages = PaywallConfigService.shared.config.messages
- messageLabel.stringValue = message
- retryButton.isHidden = false
- retryButton.isEnabled = !isRetrying
- retryButton.updateTitle(isRetrying ? messages.retrying : messages.retry)
- }
- func refreshAppearance() {
- messageLabel.textColor = AppTheme.textSecondary
- retryButton.refreshAppearance()
- }
- @objc private func retryTapped() {
- onRetry?()
- }
- }
- // MARK: - Close Button
- private final class PaywallCloseButton: NSButton, AppearanceRefreshable {
- private var hoverTracker: HoverTracker?
- private var isHovered = false
- init() {
- super.init(frame: .zero)
- isBordered = false
- bezelStyle = .inline
- translatesAutoresizingMaskIntoConstraints = false
- wantsLayer = true
- layer?.cornerRadius = 15
- layer?.borderWidth = 1.5
- if let image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close") {
- let config = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
- self.image = image.withSymbolConfiguration(config)
- }
- refreshAppearance()
- hoverTracker = HoverTracker(view: self) { [weak self] hovering in
- self?.setHovered(hovering)
- }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func refreshAppearance() {
- updateAppearance()
- }
- private func setHovered(_ hovering: Bool) {
- isHovered = hovering
- animateHover {
- updateAppearance()
- layer?.transform = hovering
- ? CATransform3DMakeScale(1.06, 1.06, 1)
- : CATransform3DIdentity
- }
- }
- private func updateAppearance() {
- if isHovered {
- layer?.backgroundColor = AppTheme.elevatedBackground.cgColor
- layer?.borderColor = AppTheme.paywallAccent.withAlphaComponent(0.45).cgColor
- contentTintColor = AppTheme.textPrimary
- } else {
- layer?.backgroundColor = AppTheme.paywallTrustBackground.cgColor
- layer?.borderColor = AppTheme.paywallBorder.cgColor
- contentTintColor = AppTheme.textSecondary
- }
- }
- override func resetCursorRects() {
- addCursorRect(bounds, cursor: .pointingHand)
- }
- }
- // MARK: - CTA Button
- private final class PaywallCTAButton: NSButton, AppearanceRefreshable {
- private var hoverTracker: HoverTracker?
- init() {
- super.init(frame: .zero)
- isBordered = false
- wantsLayer = true
- layer?.cornerRadius = 12
- font = AppTheme.semiboldFont(size: 15)
- translatesAutoresizingMaskIntoConstraints = false
- refreshAppearance()
- hoverTracker = HoverTracker(view: self) { [weak self] hovering in
- self?.setHovered(hovering)
- }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- func refreshAppearance() {
- layer?.backgroundColor = AppTheme.paywallCTABackground.cgColor
- contentTintColor = AppTheme.paywallCTAForeground
- }
- private func setHovered(_ hovering: Bool) {
- let base = AppTheme.paywallCTABackground
- let color = hovering ? base.blended(withFraction: 0.12, of: .black) ?? base : base
- animateHover {
- layer?.backgroundColor = color.cgColor
- layer?.transform = hovering
- ? CATransform3DMakeScale(1.02, 1.02, 1)
- : CATransform3DIdentity
- }
- }
- override func resetCursorRects() {
- addCursorRect(bounds, cursor: .pointingHand)
- }
- }
- // MARK: - Main Paywall Card
- final class PaywallView: NSView, AppearanceRefreshable {
- var onClose: (() -> Void)?
- private var selectedPlan: PaywallPlan = .yearly
- private var planCards: [PaywallPlan: PaywallPlanCard] = [:]
- private let ctaButton = PaywallCTAButton()
- private let renewalDisclosureLabel = NSTextField(wrappingLabelWithString: "")
- private let continueFreePlanLink = PaywallFooterLink(title: "")
- private let manageSubscriptionLink = PaywallFooterLink(title: "")
- private let restoreLink = PaywallFooterLink(title: "")
- private let privacyLink = PaywallFooterLink(title: "")
- private let termsLink = PaywallFooterLink(title: "")
- private let supportLink = PaywallFooterLink(title: "")
- private let premiumCloseButton = PaywallCloseButton()
- private var primaryFooterLinkCell: NSView?
- private var leftPanelTitle: NSTextField!
- private var rightTitle: NSTextField!
- private var rightSubtitle: NSTextField!
- private var featuresStack: NSStackView!
- private var featureRows: [PaywallFeatureRow] = []
- private var trustItemViews: [PaywallTrustItemView] = []
- private var trustStack: NSStackView!
- private var productsErrorView: PaywallProductsErrorView!
- private var plansStack: NSStackView!
- private var plansStackHeightConstraint: NSLayoutConstraint!
- private var productsErrorHeightConstraint: NSLayoutConstraint!
- private var storeObservers: [NSObjectProtocol] = []
- init() {
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- wantsLayer = true
- layer?.cornerRadius = 0
- setup()
- observeStoreUpdates()
- refreshConfigDisplay()
- refreshProductDisplay()
- refreshAppearance()
- }
- deinit {
- storeObservers.forEach { NotificationCenter.default.removeObserver($0) }
- }
- private func observeStoreUpdates() {
- let center = NotificationCenter.default
- storeObservers = [
- center.addObserver(forName: .storeProductsDidUpdate, object: nil, queue: .main) { [weak self] _ in
- self?.refreshProductDisplay()
- },
- center.addObserver(forName: .storeStateDidChange, object: nil, queue: .main) { [weak self] _ in
- self?.refreshProductDisplay()
- },
- center.addObserver(forName: .premiumStatusDidChange, object: nil, queue: .main) { [weak self] _ in
- self?.refreshProductDisplay()
- },
- center.addObserver(forName: .paywallConfigDidUpdate, object: nil, queue: .main) { [weak self] _ in
- self?.refreshConfigDisplay()
- self?.refreshProductDisplay()
- },
- ]
- }
- private var paywallConfig: PaywallConfig {
- PaywallConfigService.shared.config
- }
- private func refreshConfigDisplay() {
- let config = paywallConfig
- leftPanelTitle?.stringValue = config.leftPanelTitle
- rightTitle?.stringValue = config.rightTitle
- rightSubtitle?.stringValue = config.rightSubtitle
- syncFeatureRows(with: config.features)
- syncTrustItems(with: config.trustItems)
- continueFreePlanLink.updateTitle(config.footer.continueFree)
- manageSubscriptionLink.updateTitle(config.footer.manageSubscription)
- restoreLink.updateTitle(config.footer.restorePurchase)
- privacyLink.updateTitle(config.footer.privacyPolicy)
- termsLink.updateTitle(config.footer.termsOfService)
- supportLink.updateTitle(config.footer.support)
- }
- private func syncFeatureRows(with features: [String]) {
- guard let featuresStack else { return }
- while featureRows.count < features.count {
- let row = PaywallFeatureRow(text: "")
- featureRows.append(row)
- featuresStack.addArrangedSubview(row)
- }
- while featureRows.count > features.count {
- let row = featureRows.removeLast()
- featuresStack.removeArrangedSubview(row)
- row.removeFromSuperview()
- }
- for (index, text) in features.enumerated() {
- featureRows[index].updateText(text)
- }
- }
- private func syncTrustItems(with items: [PaywallConfig.TrustItem]) {
- for (index, item) in items.enumerated() where index < trustItemViews.count {
- trustItemViews[index].update(
- iconName: item.icon,
- title: item.title,
- subtitle: item.subtitle
- )
- }
- }
- private func refreshProductDisplay() {
- let store = StoreManager.shared
- let config = paywallConfig
- for (plan, card) in planCards {
- let product = store.product(for: plan)
- card.updateDisplay(
- product: product,
- config: config,
- introOffer: store.eligibleIntroOffer(for: plan)
- )
- }
- ctaButton.title = selectedPlan.localizedCTATitle(
- from: store.product(for: selectedPlan),
- config: config,
- introOffer: store.eligibleIntroOffer(for: selectedPlan)
- )
- updateRenewalDisclosure(
- selectedPlan.localizedRenewalDisclosure(
- from: store.product(for: selectedPlan),
- config: config,
- introOffer: store.eligibleIntroOffer(for: selectedPlan)
- )
- )
- refreshTrustItemsForSelectedPlan()
- refreshProductsErrorState()
- refreshPurchaseState()
- }
- private func refreshProductsErrorState() {
- let store = StoreManager.shared
- let hasLoadFailure = store.productLoadError != nil && store.products.isEmpty
- let isRetrying = hasLoadFailure && store.isLoadingProducts
- productsErrorView.isHidden = !hasLoadFailure
- plansStack.isHidden = hasLoadFailure
- plansStackHeightConstraint.constant = hasLoadFailure ? 0 : plansAreaHeight
- productsErrorHeightConstraint.constant = hasLoadFailure ? productsErrorAreaHeight : 0
- if hasLoadFailure, let error = store.productLoadError {
- productsErrorView.update(message: error, isRetrying: isRetrying)
- }
- }
- private var plansAreaHeight: CGFloat {
- let cardHeight: CGFloat = 86
- let spacing: CGFloat = 12
- let planCount = CGFloat(PaywallPlan.allCases.count)
- return planCount * cardHeight + max(0, planCount - 1) * spacing
- }
- private var productsErrorAreaHeight: CGFloat { 86 }
- private func refreshPurchaseState() {
- let store = StoreManager.shared
- let hasProductLoadFailure = store.productLoadError != nil && store.products.isEmpty
- let isProductReady = store.product(for: selectedPlan) != nil
- let isBusy = store.isPurchasing || store.isLoadingProducts
- let isDisabled = isBusy || !isProductReady || hasProductLoadFailure
- ctaButton.isEnabled = !isDisabled
- ctaButton.alphaValue = isDisabled ? 0.65 : 1
- refreshPrimaryFooterLink()
- }
- private func refreshPrimaryFooterLink() {
- let store = StoreManager.shared
- let showContinue = !store.isPro
- let showManage = store.hasActiveSubscription
- continueFreePlanLink.isHidden = !showContinue
- manageSubscriptionLink.isHidden = !showManage
- premiumCloseButton.isHidden = !store.isPro
- primaryFooterLinkCell?.isHidden = !showContinue && !showManage
- primaryFooterLinkCell?.needsLayout = true
- primaryFooterLinkCell?.layoutSubtreeIfNeeded()
- }
- private func refreshTrustItemsForSelectedPlan() {
- guard trustItemViews.count > 1, paywallConfig.trustItems.count > 1 else { return }
- let cancelItem = paywallConfig.trustItems[1]
- if selectedPlan == .lifetime {
- let item = paywallConfig.lifetimeTrustItem
- trustItemViews[1].update(
- iconName: item.icon,
- title: item.title,
- subtitle: item.subtitle
- )
- } else {
- trustItemViews[1].update(
- iconName: cancelItem.icon,
- title: cancelItem.title,
- subtitle: cancelItem.subtitle
- )
- }
- }
- func refreshStoreState() {
- refreshProductDisplay()
- }
- override func layout() {
- super.layout()
- let width = renewalDisclosureLabel.bounds.width
- guard width > 0, renewalDisclosureLabel.preferredMaxLayoutWidth != width else { return }
- renewalDisclosureLabel.preferredMaxLayoutWidth = width
- renewalDisclosureLabel.invalidateIntrinsicContentSize()
- }
- private func updateRenewalDisclosure(_ text: String) {
- renewalDisclosureLabel.stringValue = text
- renewalDisclosureLabel.invalidateIntrinsicContentSize()
- needsLayout = true
- }
- func refreshAppearance() {
- layer?.backgroundColor = AppTheme.paywallBackground.cgColor
- leftPanelTitle?.refreshThemeLabelColor()
- rightTitle?.refreshThemeLabelColor()
- rightSubtitle?.refreshThemeLabelColor()
- renewalDisclosureLabel.textColor = AppTheme.textSecondary
- trustStack?.layer?.backgroundColor = AppTheme.paywallTrustBackground.cgColor
- trustStack?.layer?.borderColor = AppTheme.paywallBorder.cgColor
- ctaButton.refreshAppearance()
- subviews.forEach { $0.refreshAppearanceRecursively() }
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- private func setup() {
- let leftPanel = makeLeftPanel()
- let rightPanel = makeRightPanel()
- premiumCloseButton.target = self
- premiumCloseButton.action = #selector(premiumCloseTapped)
- premiumCloseButton.isHidden = true
- addSubview(leftPanel)
- addSubview(rightPanel)
- addSubview(premiumCloseButton)
- NSLayoutConstraint.activate([
- leftPanel.leadingAnchor.constraint(equalTo: leadingAnchor),
- leftPanel.topAnchor.constraint(equalTo: topAnchor),
- leftPanel.bottomAnchor.constraint(equalTo: bottomAnchor),
- leftPanel.widthAnchor.constraint(equalToConstant: 320),
- rightPanel.leadingAnchor.constraint(equalTo: leftPanel.trailingAnchor),
- rightPanel.trailingAnchor.constraint(equalTo: trailingAnchor),
- rightPanel.topAnchor.constraint(equalTo: topAnchor),
- rightPanel.bottomAnchor.constraint(equalTo: bottomAnchor),
- premiumCloseButton.topAnchor.constraint(equalTo: topAnchor, constant: 16),
- premiumCloseButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
- premiumCloseButton.widthAnchor.constraint(equalToConstant: 30),
- premiumCloseButton.heightAnchor.constraint(equalToConstant: 30),
- ])
- }
- private func makeLeftPanel() -> NSView {
- let panel = PaywallLeftPanelView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let config = paywallConfig
- let title = NSTextField.themeLabel(
- config.leftPanelTitle,
- style: .primary,
- font: AppTheme.semiboldFont(size: 22)
- )
- title.maximumNumberOfLines = 2
- title.translatesAutoresizingMaskIntoConstraints = false
- leftPanelTitle = title
- let featuresStack = NSStackView()
- featuresStack.orientation = .vertical
- featuresStack.spacing = 6
- featuresStack.alignment = .leading
- featuresStack.translatesAutoresizingMaskIntoConstraints = false
- self.featuresStack = featuresStack
- for feature in config.features {
- let row = PaywallFeatureRow(text: feature)
- featureRows.append(row)
- featuresStack.addArrangedSubview(row)
- }
- panel.addSubview(title)
- panel.addSubview(featuresStack)
- NSLayoutConstraint.activate([
- title.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- title.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -20),
- title.topAnchor.constraint(equalTo: panel.topAnchor, constant: 48),
- featuresStack.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- featuresStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -20),
- featuresStack.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 28),
- ])
- return panel
- }
- private func makeRightPanel() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let config = paywallConfig
- let title = NSTextField.themeLabel(
- config.rightTitle,
- style: .primary,
- font: AppTheme.semiboldFont(size: 26)
- )
- title.alignment = .center
- title.translatesAutoresizingMaskIntoConstraints = false
- rightTitle = title
- let subtitle = NSTextField.themeLabel(
- config.rightSubtitle,
- style: .secondary,
- font: AppTheme.regularFont(size: 13)
- )
- subtitle.alignment = .center
- subtitle.maximumNumberOfLines = 2
- subtitle.translatesAutoresizingMaskIntoConstraints = false
- rightSubtitle = subtitle
- let plansStack = NSStackView()
- plansStack.orientation = .vertical
- plansStack.spacing = 12
- plansStack.translatesAutoresizingMaskIntoConstraints = false
- self.plansStack = plansStack
- let plansAreaView = NSView()
- plansAreaView.translatesAutoresizingMaskIntoConstraints = false
- let productsErrorView = PaywallProductsErrorView()
- productsErrorView.isHidden = true
- productsErrorView.onRetry = { [weak self] in
- self?.retryProductLoad()
- }
- self.productsErrorView = productsErrorView
- for plan in PaywallPlan.allCases {
- let card = PaywallPlanCard(plan: plan)
- card.isChosen = plan == selectedPlan
- card.onSelect = { [weak self] in self?.selectPlan(plan) }
- planCards[plan] = card
- plansStack.addArrangedSubview(card)
- }
- ctaButton.title = selectedPlan.localizedCTATitle(
- from: StoreManager.shared.product(for: selectedPlan),
- config: config,
- introOffer: StoreManager.shared.eligibleIntroOffer(for: selectedPlan)
- )
- ctaButton.target = self
- ctaButton.action = #selector(purchaseTapped)
- ctaButton.translatesAutoresizingMaskIntoConstraints = false
- renewalDisclosureLabel.font = AppTheme.regularFont(size: 10)
- renewalDisclosureLabel.textColor = AppTheme.textSecondary
- renewalDisclosureLabel.alignment = .center
- renewalDisclosureLabel.maximumNumberOfLines = 3
- renewalDisclosureLabel.lineBreakMode = .byWordWrapping
- renewalDisclosureLabel.cell?.wraps = true
- renewalDisclosureLabel.cell?.isScrollable = false
- renewalDisclosureLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- renewalDisclosureLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
- renewalDisclosureLabel.setContentHuggingPriority(.required, for: .vertical)
- renewalDisclosureLabel.translatesAutoresizingMaskIntoConstraints = false
- updateRenewalDisclosure(
- selectedPlan.localizedRenewalDisclosure(
- from: StoreManager.shared.product(for: selectedPlan),
- config: config,
- introOffer: StoreManager.shared.eligibleIntroOffer(for: selectedPlan)
- )
- )
- let trustRow = makeTrustRow()
- let footerLinks = makeFooterLinks()
- let footerSpacer = NSView()
- footerSpacer.translatesAutoresizingMaskIntoConstraints = false
- footerSpacer.setContentHuggingPriority(.defaultLow, for: .vertical)
- footerSpacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
- plansAreaView.addSubview(plansStack)
- plansAreaView.addSubview(productsErrorView)
- plansStackHeightConstraint = plansStack.heightAnchor.constraint(equalToConstant: plansAreaHeight)
- productsErrorHeightConstraint = productsErrorView.heightAnchor.constraint(equalToConstant: 0)
- panel.addSubview(title)
- panel.addSubview(subtitle)
- panel.addSubview(plansAreaView)
- panel.addSubview(trustRow)
- panel.addSubview(ctaButton)
- panel.addSubview(renewalDisclosureLabel)
- panel.addSubview(footerSpacer)
- panel.addSubview(footerLinks)
- NSLayoutConstraint.activate([
- title.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- title.topAnchor.constraint(equalTo: panel.topAnchor, constant: 40),
- title.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- subtitle.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- subtitle.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
- plansAreaView.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- plansAreaView.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- plansAreaView.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 24),
- plansAreaView.heightAnchor.constraint(equalToConstant: plansAreaHeight),
- plansStack.leadingAnchor.constraint(equalTo: plansAreaView.leadingAnchor),
- plansStack.trailingAnchor.constraint(equalTo: plansAreaView.trailingAnchor),
- plansStack.topAnchor.constraint(equalTo: plansAreaView.topAnchor),
- plansStackHeightConstraint,
- productsErrorView.leadingAnchor.constraint(equalTo: plansAreaView.leadingAnchor),
- productsErrorView.trailingAnchor.constraint(equalTo: plansAreaView.trailingAnchor),
- productsErrorView.topAnchor.constraint(equalTo: plansAreaView.topAnchor),
- productsErrorHeightConstraint,
- trustRow.leadingAnchor.constraint(equalTo: plansAreaView.leadingAnchor),
- trustRow.trailingAnchor.constraint(equalTo: plansAreaView.trailingAnchor),
- trustRow.topAnchor.constraint(equalTo: plansAreaView.bottomAnchor, constant: 18),
- ctaButton.leadingAnchor.constraint(equalTo: plansAreaView.leadingAnchor),
- ctaButton.trailingAnchor.constraint(equalTo: plansAreaView.trailingAnchor),
- ctaButton.topAnchor.constraint(equalTo: trustRow.bottomAnchor, constant: 16),
- ctaButton.heightAnchor.constraint(equalToConstant: 48),
- renewalDisclosureLabel.leadingAnchor.constraint(equalTo: plansAreaView.leadingAnchor),
- renewalDisclosureLabel.trailingAnchor.constraint(equalTo: plansAreaView.trailingAnchor),
- renewalDisclosureLabel.topAnchor.constraint(equalTo: ctaButton.bottomAnchor, constant: 10),
- footerSpacer.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
- footerSpacer.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
- footerSpacer.topAnchor.constraint(equalTo: renewalDisclosureLabel.bottomAnchor, constant: 16),
- footerSpacer.bottomAnchor.constraint(equalTo: footerLinks.topAnchor),
- footerLinks.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- footerLinks.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- footerLinks.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -16),
- ])
- return panel
- }
- private func makeTrustRow() -> NSView {
- let config = paywallConfig
- trustItemViews = config.trustItems.map { item in
- PaywallTrustItemView(
- iconName: item.icon,
- title: item.title,
- subtitle: item.subtitle
- )
- }
- let trustStack = NSStackView(views: trustItemViews)
- trustStack.orientation = .horizontal
- trustStack.distribution = .fillEqually
- trustStack.spacing = 16
- trustStack.alignment = .top
- trustStack.translatesAutoresizingMaskIntoConstraints = false
- trustStack.wantsLayer = true
- trustStack.layer?.cornerRadius = 12
- trustStack.layer?.borderWidth = 1.5
- trustStack.layer?.masksToBounds = true
- trustStack.edgeInsets = NSEdgeInsets(top: 12, left: 14, bottom: 12, right: 14)
- trustStack.translatesAutoresizingMaskIntoConstraints = false
- trustStack.setContentHuggingPriority(.required, for: .vertical)
- trustStack.setContentCompressionResistancePriority(.required, for: .vertical)
- trustStack.heightAnchor.constraint(
- equalToConstant: PaywallTrustItemView.preferredHeight + trustStack.edgeInsets.top + trustStack.edgeInsets.bottom
- ).isActive = true
- self.trustStack = trustStack
- return trustStack
- }
- private func makeFooterLinks() -> NSView {
- let container = NSView()
- container.translatesAutoresizingMaskIntoConstraints = false
- container.setContentHuggingPriority(.required, for: .vertical)
- container.setContentCompressionResistancePriority(.required, for: .vertical)
- let config = paywallConfig
- let separator = NSView()
- separator.translatesAutoresizingMaskIntoConstraints = false
- separator.wantsLayer = true
- separator.layer?.backgroundColor = AppTheme.paywallBorder.cgColor
- continueFreePlanLink.updateTitle(config.footer.continueFree)
- continueFreePlanLink.target = self
- continueFreePlanLink.action = #selector(continueWithFreePlanTapped)
- manageSubscriptionLink.updateTitle(config.footer.manageSubscription)
- manageSubscriptionLink.target = self
- manageSubscriptionLink.action = #selector(manageSubscriptionTapped)
- let primaryCell = makePrimaryFooterLinkCell()
- primaryFooterLinkCell = primaryCell
- refreshPrimaryFooterLink()
- restoreLink.updateTitle(config.footer.restorePurchase)
- restoreLink.target = self
- restoreLink.action = #selector(restoreTapped)
- privacyLink.updateTitle(config.footer.privacyPolicy)
- privacyLink.target = self
- privacyLink.action = #selector(privacyPolicyTapped)
- termsLink.updateTitle(config.footer.termsOfService)
- termsLink.target = self
- termsLink.action = #selector(termsOfServiceTapped)
- supportLink.updateTitle(config.footer.support)
- supportLink.target = self
- supportLink.action = #selector(supportTapped)
- let linkCells = [
- primaryCell,
- makeFooterLinkCell(link: restoreLink),
- makeFooterLinkCell(link: privacyLink),
- makeFooterLinkCell(link: termsLink),
- makeFooterLinkCell(link: supportLink),
- ]
- let linksStack = NSStackView(views: linkCells)
- linksStack.orientation = .horizontal
- linksStack.spacing = 0
- linksStack.alignment = .centerY
- linksStack.distribution = .fillEqually
- linksStack.translatesAutoresizingMaskIntoConstraints = false
- container.addSubview(separator)
- container.addSubview(linksStack)
- NSLayoutConstraint.activate([
- separator.leadingAnchor.constraint(equalTo: container.leadingAnchor),
- separator.trailingAnchor.constraint(equalTo: container.trailingAnchor),
- separator.topAnchor.constraint(equalTo: container.topAnchor),
- separator.heightAnchor.constraint(equalToConstant: 1),
- linksStack.leadingAnchor.constraint(equalTo: container.leadingAnchor),
- linksStack.trailingAnchor.constraint(equalTo: container.trailingAnchor),
- linksStack.topAnchor.constraint(equalTo: separator.bottomAnchor, constant: 10),
- linksStack.bottomAnchor.constraint(equalTo: container.bottomAnchor),
- ])
- return container
- }
- private func makePrimaryFooterLinkCell() -> NSView {
- let cell = NSView()
- cell.translatesAutoresizingMaskIntoConstraints = false
- cell.setContentHuggingPriority(.required, for: .vertical)
- cell.setContentCompressionResistancePriority(.required, for: .vertical)
- for link in [continueFreePlanLink, manageSubscriptionLink] {
- cell.addSubview(link)
- NSLayoutConstraint.activate([
- link.centerXAnchor.constraint(equalTo: cell.centerXAnchor),
- link.centerYAnchor.constraint(equalTo: cell.centerYAnchor),
- link.topAnchor.constraint(equalTo: cell.topAnchor),
- link.bottomAnchor.constraint(equalTo: cell.bottomAnchor),
- ])
- }
- return cell
- }
- private func makeFooterLinkCell(link: PaywallFooterLink) -> NSView {
- let cell = NSView()
- cell.translatesAutoresizingMaskIntoConstraints = false
- cell.setContentHuggingPriority(.required, for: .vertical)
- cell.setContentCompressionResistancePriority(.required, for: .vertical)
- cell.addSubview(link)
- NSLayoutConstraint.activate([
- link.centerXAnchor.constraint(equalTo: cell.centerXAnchor),
- link.centerYAnchor.constraint(equalTo: cell.centerYAnchor),
- link.topAnchor.constraint(equalTo: cell.topAnchor),
- link.bottomAnchor.constraint(equalTo: cell.bottomAnchor),
- ])
- return cell
- }
- private func selectPlan(_ plan: PaywallPlan) {
- selectedPlan = plan
- for (key, card) in planCards {
- card.isChosen = key == plan
- }
- ctaButton.title = plan.localizedCTATitle(
- from: StoreManager.shared.product(for: plan),
- config: paywallConfig,
- introOffer: StoreManager.shared.eligibleIntroOffer(for: plan)
- )
- updateRenewalDisclosure(
- plan.localizedRenewalDisclosure(
- from: StoreManager.shared.product(for: plan),
- config: paywallConfig,
- introOffer: StoreManager.shared.eligibleIntroOffer(for: plan)
- )
- )
- refreshTrustItemsForSelectedPlan()
- refreshPurchaseState()
- }
- private func retryProductLoad() {
- Task { @MainActor in
- refreshProductsErrorState()
- refreshPurchaseState()
- await StoreManager.shared.loadProducts()
- refreshStoreState()
- }
- }
- @objc private func purchaseTapped() {
- Task { @MainActor in
- refreshPurchaseState()
- do {
- let outcome = try await StoreManager.shared.purchase(plan: selectedPlan)
- refreshStoreState()
- switch outcome {
- case .purchased, .cancelled:
- break
- case .pending:
- let messages = paywallConfig.messages
- StoreManager.shared.showAlert(
- title: messages.pendingPurchaseTitle,
- message: messages.pendingPurchaseMessage,
- on: window
- )
- }
- } catch {
- refreshPurchaseState()
- StoreManager.shared.showPurchaseError(error, on: window)
- }
- }
- }
- @objc private func restoreTapped() {
- Task { @MainActor in
- refreshPurchaseState()
- do {
- let restored = try await StoreManager.shared.restorePurchases()
- refreshStoreState()
- if !restored {
- let messages = paywallConfig.messages
- StoreManager.shared.showAlert(
- title: messages.restoreNotFoundTitle,
- message: messages.restoreNotFoundMessage,
- on: window
- )
- }
- } catch {
- refreshPurchaseState()
- StoreManager.shared.showPurchaseError(error, on: window)
- }
- }
- }
- @objc private func continueWithFreePlanTapped() {
- onClose?()
- }
- @objc private func premiumCloseTapped() {
- onClose?()
- }
- @objc private func manageSubscriptionTapped() {
- StoreManager.shared.showManageSubscriptions()
- }
- @objc private func privacyPolicyTapped() {
- openExternalLink(paywallConfig.urls.privacy)
- }
- @objc private func termsOfServiceTapped() {
- openExternalLink(paywallConfig.urls.terms)
- }
- @objc private func supportTapped() {
- openExternalLink(paywallConfig.urls.support)
- }
- private func openExternalLink(_ urlString: String) {
- guard let url = URL(string: urlString) else { return }
- NSWorkspace.shared.open(url)
- }
- }
- // MARK: - Overlay Presenter
- final class PaywallOverlayView: NSView, AppearanceRefreshable {
- var onDismiss: (() -> Void)?
- private let paywallView: PaywallView
- private let blurView = NSVisualEffectView()
- private let backdrop = NSView()
- private let pattern = WavePatternView()
- private var acceptsHitTesting = false
- init() {
- paywallView = PaywallView()
- super.init(frame: .zero)
- translatesAutoresizingMaskIntoConstraints = false
- setup()
- refreshAppearance()
- }
- func refreshAppearance() {
- backdrop.layer?.backgroundColor = AppTheme.paywallOverlayBackdrop.cgColor
- blurView.material = AppSettings.darkModeEnabled ? .hudWindow : .underWindowBackground
- pattern.refreshAppearance()
- paywallView.refreshAppearance()
- }
- func refreshStoreState() {
- paywallView.refreshStoreState()
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) { nil }
- override func hitTest(_ point: NSPoint) -> NSView? {
- guard acceptsHitTesting else { return nil }
- return super.hitTest(point)
- }
- private func setup() {
- blurView.translatesAutoresizingMaskIntoConstraints = false
- blurView.material = .underWindowBackground
- blurView.blendingMode = .withinWindow
- blurView.state = .active
- backdrop.translatesAutoresizingMaskIntoConstraints = false
- backdrop.wantsLayer = true
- backdrop.layer?.backgroundColor = NSColor(calibratedWhite: 0.15, alpha: 0.22).cgColor
- pattern.translatesAutoresizingMaskIntoConstraints = false
- pattern.alphaValue = 0.35
- paywallView.translatesAutoresizingMaskIntoConstraints = false
- paywallView.onClose = { [weak self] in self?.dismiss() }
- addSubview(blurView)
- addSubview(backdrop)
- backdrop.addSubview(pattern)
- addSubview(paywallView)
- NSLayoutConstraint.activate([
- blurView.leadingAnchor.constraint(equalTo: leadingAnchor),
- blurView.trailingAnchor.constraint(equalTo: trailingAnchor),
- blurView.topAnchor.constraint(equalTo: topAnchor),
- blurView.bottomAnchor.constraint(equalTo: bottomAnchor),
- backdrop.leadingAnchor.constraint(equalTo: leadingAnchor),
- backdrop.trailingAnchor.constraint(equalTo: trailingAnchor),
- backdrop.topAnchor.constraint(equalTo: topAnchor),
- backdrop.bottomAnchor.constraint(equalTo: bottomAnchor),
- pattern.leadingAnchor.constraint(equalTo: backdrop.leadingAnchor),
- pattern.trailingAnchor.constraint(equalTo: backdrop.trailingAnchor),
- pattern.topAnchor.constraint(equalTo: backdrop.topAnchor),
- pattern.bottomAnchor.constraint(equalTo: backdrop.bottomAnchor),
- paywallView.leadingAnchor.constraint(equalTo: leadingAnchor),
- paywallView.trailingAnchor.constraint(equalTo: trailingAnchor),
- paywallView.topAnchor.constraint(equalTo: topAnchor),
- paywallView.bottomAnchor.constraint(equalTo: bottomAnchor),
- ])
- }
- func present(in parent: NSView) {
- guard superview == nil else { return }
- if let window = parent.window,
- let windowFrameView = window.contentView?.superview {
- windowFrameView.addSubview(self)
- NSLayoutConstraint.activate([
- leadingAnchor.constraint(equalTo: windowFrameView.leadingAnchor),
- trailingAnchor.constraint(equalTo: windowFrameView.trailingAnchor),
- topAnchor.constraint(equalTo: windowFrameView.topAnchor),
- bottomAnchor.constraint(equalTo: windowFrameView.bottomAnchor),
- ])
- } else {
- parent.addSubview(self)
- NSLayoutConstraint.activate([
- leadingAnchor.constraint(equalTo: parent.leadingAnchor),
- trailingAnchor.constraint(equalTo: parent.trailingAnchor),
- topAnchor.constraint(equalTo: parent.topAnchor),
- bottomAnchor.constraint(equalTo: parent.bottomAnchor),
- ])
- }
- alphaValue = 1
- acceptsHitTesting = true
- paywallView.refreshStoreState()
- Task { @MainActor in
- if StoreManager.shared.isResolvingEntitlements {
- await StoreManager.shared.ensureEntitlementsResolved()
- paywallView.refreshStoreState()
- }
- if StoreManager.shared.products.isEmpty, !StoreManager.shared.isLoadingProducts {
- await StoreManager.shared.loadProducts()
- paywallView.refreshStoreState()
- }
- }
- Task { @MainActor in
- await PaywallConfigService.shared.refreshFromRemote()
- }
- }
- func dismiss() {
- acceptsHitTesting = false
- NSAnimationContext.runAnimationGroup({ context in
- context.duration = 0.15
- animator().alphaValue = 0
- }, completionHandler: { [weak self] in
- self?.removeFromSuperview()
- self?.onDismiss?()
- })
- }
- }
|