Sources/Orgstar/StoreViews.swift

210 lines · 8765 bytes

7 symbols in this file
  1#if APPSTORE
  2import OrgApp
  3import StoreKit
  4import SwiftUI
  5
  6/// orgstar+ from the App Store: status, plans with their prices and renewal terms, restoring,
  7/// managing a subscription, and tips.
  8struct StoreForm: View {
  9    /// The feature that led here, if any.
 10    var feature: ProFeature?
 11    /// Whether to show the tips section, which the paywall leaves out.
 12    var showsTips = true
 13    private var store: ProStore { .shared }
 14    private var access: ProAccess { .shared }
 15
 16    static let termsURL = URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!
 17    static let privacyURL = URL(string: "https://krz.sh/privacy/orgstar/")!
 18    static let subscriptionsURL = URL(string: "https://apps.apple.com/account/subscriptions")!
 19
 20    var body: some View {
 21        Form {
 22            Section {
 23                HStack(spacing: 12) {
 24                    Image(systemName: "star.fill")
 25                        .font(.title2)
 26                        .foregroundStyle(.white)
 27                        .frame(width: 40, height: 40)
 28                        .background(.orange.gradient, in: .rect(cornerRadius: 9))
 29                        .accessibilityHidden(true)
 30                    VStack(alignment: .leading, spacing: 2) {
 31                        if let feature, !access.isUnlocked {
 32                            Text("\(feature.storeTitle) needs orgstar+.").font(.headline)
 33                        } else {
 34                            Text(verbatim: "orgstar+").font(.headline)
 35                        }
 36                        Text(status).foregroundStyle(.secondary)
 37                    }
 38                }
 39            }
 40            Section {
 41                ForEach(ProFeature.macFeatures) { feature in
 42                    Label(feature.storeTitle, systemImage: feature.systemImage)
 43                }
 44            } header: {
 45                Text("Included in orgstar+")
 46            } footer: {
 47                Text("Editing, the agenda, capture, clocking, tables and search stay free.").settingsFooter()
 48            }
 49            if store.activeProductID != ProStore.lifetime {
 50                Section {
 51                    if store.isLoading && store.products.isEmpty {
 52                        ProgressView().frame(maxWidth: .infinity)
 53                    }
 54                    ForEach(store.products) { product in plan(product) }
 55                    if !store.isLoading && store.message != nil && store.products.count < ProStore.productIDs.count {
 56                        Button("Try Again") { Task { await store.loadProducts() } }
 57                    }
 58                } header: {
 59                    Text("Choose a plan")
 60                } footer: {
 61                    Text("Subscriptions renew automatically until cancelled in your Apple Account settings, at least 24 hours before the period ends.")
 62                        .settingsFooter()
 63                }
 64            }
 65            Section {
 66                HStack {
 67                    Button("Restore Purchases") { Task { await store.restore() } }.disabled(store.busy)
 68                    if store.activeProductID == ProStore.monthly || store.activeProductID == ProStore.yearly {
 69                        Link("Manage Subscription…", destination: Self.subscriptionsURL)
 70                    }
 71                    Spacer()
 72                    Link("Terms of Use", destination: Self.termsURL)
 73                    Link("Privacy Policy", destination: Self.privacyURL)
 74                }
 75                if let message = store.message {
 76                    Text(message).foregroundStyle(.secondary)
 77                }
 78            }
 79            if showsTips {
 80                StoreTipSection()
 81            }
 82        }
 83        .formStyle(.grouped)
 84        .task { await store.loadProducts() }
 85    }
 86
 87    /// One plan: its name, an optional savings tag, what it bills, and a button with its price.
 88    private func plan(_ product: Product) -> some View {
 89        LabeledContent {
 90            Button(price(product)) { Task { await store.buy(product) } }
 91                .monospacedDigit()
 92                .disabled(store.busy || product.id == store.activeProductID)
 93        } label: {
 94            HStack(spacing: 6) {
 95                Text(product.displayName)
 96                if let percent = savings(product) {
 97                    Text("Save \(percent)%")
 98                        .font(.caption.bold())
 99                        .foregroundStyle(.white)
100                        .padding(.horizontal, 6)
101                        .padding(.vertical, 1)
102                        .background(.orange.gradient, in: .capsule)
103                }
104            }
105            Text(detail(product))
106        }
107    }
108
109    private func detail(_ product: Product) -> String {
110        if product.id == store.activeProductID { return String(localized: "Current plan") }
111        switch product.id {
112        case ProStore.monthly: return String(localized: "Billed monthly")
113        case ProStore.yearly:
114            let perMonth = (product.price / 12).formatted(product.priceFormatStyle)
115            return String(localized: "\(perMonth) a month, billed yearly")
116        default: return String(localized: "One payment, no subscription")
117        }
118    }
119
120    /// The price with its billing period.
121    private func price(_ product: Product) -> String {
122        switch product.subscription?.subscriptionPeriod.unit {
123        case .month: String(localized: "\(product.displayPrice) / month")
124        case .year: String(localized: "\(product.displayPrice) / year")
125        default: product.displayPrice
126        }
127    }
128
129    private func savings(_ product: Product) -> Int? {
130        guard product.id == ProStore.yearly,
131              let monthly = store.products.first(where: { $0.id == ProStore.monthly })
132        else { return nil }
133        return ProStore.yearlySavings(yearly: product.price, monthly: monthly.price)
134    }
135
136    private var status: String {
137        guard access.isUnlocked else { return String(localized: "Power features and Apple integrations, on top of everything that stays free.") }
138        return store.activeProductID == ProStore.lifetime
139            ? String(localized: "You own orgstar+. Thank you for supporting orgstar.")
140            : String(localized: "Your orgstar+ subscription is active. Thank you for supporting orgstar.")
141    }
142}
143
144/// Tips, for everyone, with or without orgstar+.
145struct StoreTipSection: View {
146    @State private var store = TipStore()
147
148    var body: some View {
149        Section {
150            if store.isLoading && store.products.isEmpty {
151                ProgressView().frame(maxWidth: .infinity)
152            }
153            ForEach(store.products) { product in
154                LabeledContent(product.displayName) {
155                    if store.purchasingProductID == product.id {
156                        ProgressView().controlSize(.small)
157                    } else {
158                        Button(product.displayPrice) { Task { await store.purchase(product) } }
159                            .monospacedDigit()
160                            .disabled(store.purchasingProductID != nil)
161                    }
162                }
163            }
164            if let message = store.message {
165                Text(message).foregroundStyle(.secondary)
166                if store.products.count < Tip.productIDs.count {
167                    Button("Try Again") { Task { await store.loadProducts() } }.disabled(store.isLoading)
168                }
169            }
170        } header: {
171            Text("Support Development")
172        } footer: {
173            Text("Tips are one-time purchases that help pay for orgstar's development. They don't unlock anything.")
174                .settingsFooter()
175        }
176        .task { await store.loadProducts() }
177        .alert("Thank You", isPresented: $store.thanked) {
178            Button("OK") {}
179        } message: {
180            Text("Your tip helps keep orgstar going.")
181        }
182    }
183}
184
185/// Shown when a Pro feature is used without Pro.
186struct StorePaywallSheet: View {
187    let feature: ProFeature
188    @Environment(\.dismiss) private var dismiss
189
190    var body: some View {
191        VStack(spacing: 0) {
192            StoreForm(feature: feature, showsTips: false)
193            HStack {
194                Spacer()
195                Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
196            }
197            .padding([.horizontal, .bottom], 20)
198        }
199        .frame(width: 520, height: 600)
200        .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
201    }
202}
203
204extension ProFeature {
205    /// The title in the App Store build, which runs Emacs Lisp blocks natively.
206    var storeTitle: String {
207        self == .babel ? String(localized: "Run Emacs Lisp blocks and tangle") : title
208    }
209}
210#endif