-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubKitViews.swift
More file actions
655 lines (586 loc) · 19.6 KB
/
SubKitViews.swift
File metadata and controls
655 lines (586 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import StoreKit
import SubKit
import SwiftUI
import Observation
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *)
private enum ProductLoadState<Value> {
case loading
case loaded(Value)
case empty
case failed(String)
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *)
public struct SubKitProductView: View {
private let productID: Product.ID
private let appAccountToken: UUID?
private let prefersPromotionalIcon: Bool
private let icon: (() -> AnyView)?
private let placeholderIcon: (() -> AnyView)?
@State private var loadState = ProductLoadState<Product>.loading
public init(
id productID: Product.ID,
appAccountToken: UUID? = nil,
prefersPromotionalIcon: Bool = false
) {
self.productID = productID
self.appAccountToken = appAccountToken
self.prefersPromotionalIcon = prefersPromotionalIcon
self.icon = nil
self.placeholderIcon = nil
}
public init<Icon: View>(
id productID: Product.ID,
appAccountToken: UUID? = nil,
prefersPromotionalIcon: Bool = false,
@ViewBuilder icon: @escaping () -> Icon
) {
self.productID = productID
self.appAccountToken = appAccountToken
self.prefersPromotionalIcon = prefersPromotionalIcon
self.icon = { AnyView(icon()) }
self.placeholderIcon = nil
}
public init<Icon: View, Placeholder: View>(
id productID: Product.ID,
appAccountToken: UUID? = nil,
prefersPromotionalIcon: Bool = false,
@ViewBuilder icon: @escaping () -> Icon,
@ViewBuilder placeholderIcon: @escaping () -> Placeholder
) {
self.productID = productID
self.appAccountToken = appAccountToken
self.prefersPromotionalIcon = prefersPromotionalIcon
self.icon = { AnyView(icon()) }
self.placeholderIcon = { AnyView(placeholderIcon()) }
}
public var body: some View {
Group {
switch self.loadState {
case .loading:
ProgressView()
case let .loaded(product):
self.productView(product)
case .empty:
ContentUnavailableView(
"Product Unavailable",
systemImage: "shippingbox",
description: Text("This product is unavailable in the current storefront.")
)
case let .failed(message):
ContentUnavailableView(
"Product Unavailable",
systemImage: "exclamationmark.triangle",
description: Text(message)
)
}
}
.task(id: self.productID) {
await self.loadTask()
}
.inAppPurchaseOptions { _ in
self.purchaseOptions()
}
}
@ViewBuilder
private func productView(_ product: Product) -> some View {
if let icon = self.icon, let placeholderIcon = self.placeholderIcon {
ProductView(
id: product.id,
prefersPromotionalIcon: self.prefersPromotionalIcon,
icon: { icon() },
placeholderIcon: { placeholderIcon() }
)
} else if let icon = self.icon {
ProductView(
product,
prefersPromotionalIcon: self.prefersPromotionalIcon,
icon: { icon() }
)
} else {
ProductView(product, prefersPromotionalIcon: self.prefersPromotionalIcon)
}
}
private func loadTask() async {
self.loadState = .loading
do {
let products = try await Product.products(for: [self.productID])
guard let product = products.first else {
self.loadState = .empty
return
}
self.loadState = .loaded(product)
} catch {
self.loadState = .failed(self.errorDescription(error))
}
}
private func errorDescription(_ error: some Error) -> String {
if let error = error as? LocalizedError, let description = error.errorDescription {
return description
}
return String(describing: error)
}
private func purchaseOptions() -> Set<Product.PurchaseOption> {
guard let appAccountToken = self.appAccountToken else {
return []
}
return [.appAccountToken(appAccountToken)]
}
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *)
public struct SubKitStoreView: View {
private let productIDs: [Product.ID]
private let appAccountToken: UUID?
private let prefersPromotionalIcon: Bool
private let icon: ((Product) -> AnyView)?
@State private var loadState = ProductLoadState<[Product]>.loading
public init(
ids productIDs: some Collection<Product.ID>,
appAccountToken: UUID? = nil,
prefersPromotionalIcon: Bool = false
) {
self.productIDs = Array(productIDs)
self.appAccountToken = appAccountToken
self.prefersPromotionalIcon = prefersPromotionalIcon
self.icon = nil
}
public init<Icon: View>(
ids productIDs: some Collection<Product.ID>,
appAccountToken: UUID? = nil,
prefersPromotionalIcon: Bool = false,
@ViewBuilder icon: @escaping (Product) -> Icon
) {
self.productIDs = Array(productIDs)
self.appAccountToken = appAccountToken
self.prefersPromotionalIcon = prefersPromotionalIcon
self.icon = { AnyView(icon($0)) }
}
public var body: some View {
Group {
switch self.loadState {
case .loading:
ProgressView()
case let .loaded(products):
self.storeView(products)
case .empty:
ContentUnavailableView(
"Store Unavailable",
systemImage: "basket",
description: Text("No products are available in the current storefront.")
)
case let .failed(message):
ContentUnavailableView(
"Store Unavailable",
systemImage: "exclamationmark.triangle",
description: Text(message)
)
}
}
.task(id: self.productIDs) {
await self.loadTask()
}
.inAppPurchaseOptions { _ in
self.purchaseOptions()
}
}
@ViewBuilder
private func storeView(_ products: [Product]) -> some View {
if let icon = self.icon {
StoreView(
products: products,
prefersPromotionalIcon: self.prefersPromotionalIcon,
icon: { product in
icon(product)
}
)
} else {
StoreView(products: products, prefersPromotionalIcon: self.prefersPromotionalIcon)
}
}
private func loadTask() async {
guard !self.productIDs.isEmpty else {
self.loadState = .empty
return
}
self.loadState = .loading
do {
let products = try await Product.products(for: self.productIDs)
self.loadState = products.isEmpty ? .empty : .loaded(products.sorted(by: self.sortProducts))
} catch {
self.loadState = .failed(self.errorDescription(error))
}
}
private func sortProducts(_ lhs: Product, _ rhs: Product) -> Bool {
if lhs.price == rhs.price {
return lhs.id < rhs.id
}
return lhs.price < rhs.price
}
private func errorDescription(_ error: some Error) -> String {
if let error = error as? LocalizedError, let description = error.errorDescription {
return description
}
return String(describing: error)
}
private func purchaseOptions() -> Set<Product.PurchaseOption> {
guard let appAccountToken = self.appAccountToken else {
return []
}
return [.appAccountToken(appAccountToken)]
}
}
@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *)
public struct SubKitSubscriptionStoreView: View {
private enum Source {
case groupID(String)
case productIDs([Product.ID])
}
private let source: Source
private let appAccountToken: UUID?
private let visibleRelationships: Product.SubscriptionRelationship
private let marketingContent: (() -> AnyView)?
@State private var loadState = ProductLoadState<[Product]>.loading
public init(
groupID: String,
appAccountToken: UUID? = nil,
visibleRelationships: Product.SubscriptionRelationship = .all
) {
self.source = .groupID(groupID)
self.appAccountToken = appAccountToken
self.visibleRelationships = visibleRelationships
self.marketingContent = nil
}
public init<Content: View>(
groupID: String,
appAccountToken: UUID? = nil,
visibleRelationships: Product.SubscriptionRelationship = .all,
@ViewBuilder marketingContent: @escaping () -> Content
) {
self.source = .groupID(groupID)
self.appAccountToken = appAccountToken
self.visibleRelationships = visibleRelationships
self.marketingContent = { AnyView(marketingContent()) }
}
public init(productIDs: some Collection<Product.ID>, appAccountToken: UUID? = nil) {
self.source = .productIDs(Array(productIDs))
self.appAccountToken = appAccountToken
self.visibleRelationships = .all
self.marketingContent = nil
}
public init<Content: View>(
productIDs: some Collection<Product.ID>,
appAccountToken: UUID? = nil,
@ViewBuilder marketingContent: @escaping () -> Content
) {
self.source = .productIDs(Array(productIDs))
self.appAccountToken = appAccountToken
self.visibleRelationships = .all
self.marketingContent = { AnyView(marketingContent()) }
}
public var body: some View {
Group {
switch self.source {
case .groupID:
self.groupBackedView
case .productIDs:
self.productBackedView
}
}
.inAppPurchaseOptions { _ in
self.purchaseOptions()
}
}
@ViewBuilder
private var groupBackedView: some View {
if case let .groupID(groupID) = self.source {
if let marketingContent = self.marketingContent {
SubscriptionStoreView(
groupID: groupID,
visibleRelationships: self.visibleRelationships
) {
marketingContent()
}
} else {
SubscriptionStoreView(
groupID: groupID,
visibleRelationships: self.visibleRelationships
)
}
}
}
@ViewBuilder
private var productBackedView: some View {
switch self.loadState {
case .loading:
ProgressView()
.task {
await self.productTask()
}
case let .loaded(products):
self.subscriptionStoreView(products)
case .empty:
ContentUnavailableView(
"Subscription Unavailable",
systemImage: "creditcard",
description: Text("The subscription is unavailable in the current storefront.")
)
case let .failed(message):
ContentUnavailableView(
"Subscription Unavailable",
systemImage: "exclamationmark.triangle",
description: Text(message)
)
}
}
@ViewBuilder
private func subscriptionStoreView(_ products: [Product]) -> some View {
if let marketingContent = self.marketingContent {
SubscriptionStoreView(subscriptions: products) {
marketingContent()
}
} else {
SubscriptionStoreView(subscriptions: products)
}
}
private func productTask() async {
guard case let .productIDs(productIDs) = self.source else {
return
}
guard !productIDs.isEmpty else {
self.loadState = .empty
return
}
self.loadState = .loading
do {
let products = try await Product.products(for: productIDs)
.filter { $0.type == .autoRenewable }
self.loadState = products.isEmpty ? .empty : .loaded(products.sorted(by: self.sortProducts))
} catch {
self.loadState = .failed(self.errorDescription(error))
}
}
private func sortProducts(_ lhs: Product, _ rhs: Product) -> Bool {
if lhs.price == rhs.price {
return lhs.id < rhs.id
}
return lhs.price < rhs.price
}
private func errorDescription(_ error: some Error) -> String {
if let error = error as? LocalizedError, let description = error.errorDescription {
return description
}
return String(describing: error)
}
private func purchaseOptions() -> Set<Product.PurchaseOption> {
guard let appAccountToken = self.appAccountToken else {
return []
}
return [.appAccountToken(appAccountToken)]
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@MainActor
@Observable
public final class SubKitManageSubscriptionsModel {
public var isPresented = false
public let subscriptionGroupID: String?
public init(subscriptionGroupID: String? = nil) {
self.subscriptionGroupID = subscriptionGroupID
}
public func present() {
self.isPresented = true
}
public func dismiss() {
self.isPresented = false
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct SubKitManageSubscriptionsPresenter: View {
public let model: SubKitManageSubscriptionsModel
public init(model: SubKitManageSubscriptionsModel) {
self.model = model
}
public var body: some View {
@Bindable var model = self.model
Color.clear
.ignoresSafeArea()
.allowsHitTesting(false)
.modifier(ManageSubscriptionsSheetModifier(
isPresented: $model.isPresented,
subscriptionGroupID: model.subscriptionGroupID
))
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public struct SubKitManageSubscriptionsButton<Label: View>: View {
private enum Source {
case external(SubKitManageSubscriptionsModel)
case owned(String?)
}
private let source: Source
private let label: () -> Label
public init(
model: SubKitManageSubscriptionsModel,
@ViewBuilder label: @escaping () -> Label
) {
self.source = .external(model)
self.label = label
}
public init(
subscriptionGroupID: String? = nil,
@ViewBuilder label: @escaping () -> Label
) {
self.source = .owned(subscriptionGroupID)
self.label = label
}
@ViewBuilder
public var body: some View {
switch self.source {
case let .external(model):
ExternalManageSubscriptionsButton(model: model, label: self.label)
case let .owned(subscriptionGroupID):
OwnedManageSubscriptionsButton(
subscriptionGroupID: subscriptionGroupID,
label: self.label
)
}
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
private struct ExternalManageSubscriptionsButton<Label: View>: View {
let model: SubKitManageSubscriptionsModel
private let label: () -> Label
init(
model: SubKitManageSubscriptionsModel,
@ViewBuilder label: @escaping () -> Label
) {
self.model = model
self.label = label
}
var body: some View {
Button(action: self.manageSubscriptionButtonTapped) {
self.label()
}
.background {
SubKitManageSubscriptionsPresenter(model: self.model)
}
}
private func manageSubscriptionButtonTapped() {
self.model.present()
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
private struct OwnedManageSubscriptionsButton<Label: View>: View {
@State private var model: SubKitManageSubscriptionsModel
private let label: () -> Label
init(
subscriptionGroupID: String?,
@ViewBuilder label: @escaping () -> Label
) {
self._model = State(
initialValue: SubKitManageSubscriptionsModel(
subscriptionGroupID: subscriptionGroupID
)
)
self.label = label
}
var body: some View {
Button(action: self.manageSubscriptionButtonTapped) {
self.label()
}
.background {
SubKitManageSubscriptionsPresenter(model: self.model)
}
}
private func manageSubscriptionButtonTapped() {
self.model.present()
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension SubKitManageSubscriptionsButton where Label == Text {
public init(
_ title: LocalizedStringKey = "Manage Subscription",
model: SubKitManageSubscriptionsModel
) {
self.init(model: model) {
Text(title)
}
}
public init(
_ title: LocalizedStringKey = "Manage Subscription",
subscriptionGroupID: String? = nil
) {
self.init(subscriptionGroupID: subscriptionGroupID) {
Text(title)
}
}
}
@available(iOS 15.0, visionOS 1.0, *)
@available(macOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
private struct ManageSubscriptionsSheetModifier: ViewModifier {
@Binding var isPresented: Bool
let subscriptionGroupID: String?
func body(content: Content) -> some View {
if let subscriptionGroupID {
if #available(iOS 17.0, *) {
content.manageSubscriptionsSheet(
isPresented: self.$isPresented,
subscriptionGroupID: subscriptionGroupID
)
} else {
content.manageSubscriptionsSheet(isPresented: self.$isPresented)
}
} else {
content.manageSubscriptionsSheet(isPresented: self.$isPresented)
}
}
}
#Preview("SubKit Product") {
if #available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) {
SubKitProductView(id: "com.example.subkit.lifetime")
.padding()
}
}
#Preview("SubKit Store") {
if #available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) {
NavigationStack {
SubKitStoreView(
ids: [
"com.example.subkit.lifetime",
"com.example.subkit.monthly",
"com.example.subkit.yearly",
]
)
.navigationTitle("SubKit")
}
}
}
#Preview("SubKit Subscription") {
if #available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) {
SubKitSubscriptionStoreView(
productIDs: [
"com.example.subkit.monthly",
"com.example.subkit.yearly",
]
)
}
}