-
Notifications
You must be signed in to change notification settings - Fork 5
/
Graphaello.swift
7330 lines (5862 loc) · 239 KB
/
Graphaello.swift
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// swiftlint:disable all
// This file was automatically generated and should not be edited.
import Apollo
import Combine
import Foundation
import SwiftUI
// MARK: Basic API
protocol Target {}
protocol API: Target {
var client: ApolloClient { get }
}
extension API {
func fetch<Query: GraphQLQuery>(query: Query, completion: @escaping (Result<Query.Data, GraphQLLoadingError<Self>>) -> Void) {
client.fetch(query: query) { result in
switch result {
case let .success(result):
guard let data = result.data else {
if let errors = result.errors, errors.count > 0 {
return completion(.failure(.graphQLErrors(errors)))
}
return completion(.failure(.emptyData(api: self)))
}
completion(.success(data))
case let .failure(error):
completion(.failure(.networkError(error)))
}
}
}
}
protocol MutationTarget: Target {}
protocol Connection: Target {
associatedtype Node
}
protocol Fragment {
associatedtype UnderlyingType
static var placeholder: Self { get }
}
extension Array: Fragment where Element: Fragment {
typealias UnderlyingType = [Element.UnderlyingType]
static var placeholder: [Element] {
return Array(repeating: Element.placeholder, count: 5)
}
}
extension Optional: Fragment where Wrapped: Fragment {
typealias UnderlyingType = Wrapped.UnderlyingType?
static var placeholder: Wrapped? {
return Wrapped.placeholder
}
}
protocol Mutation: ObservableObject {
associatedtype Value
var isLoading: Bool { get }
}
protocol CurrentValueMutation: ObservableObject {
associatedtype Value
var isLoading: Bool { get }
var value: Value { get }
var error: Error? { get }
}
// MARK: - Basic API: Paths
struct GraphQLPath<TargetType: Target, Value> {
fileprivate init() {}
}
struct GraphQLFragmentPath<TargetType: Target, UnderlyingType> {
fileprivate init() {}
}
extension GraphQLFragmentPath {
typealias Path<V> = GraphQLPath<TargetType, V>
typealias FragmentPath<V> = GraphQLFragmentPath<TargetType, V>
}
extension GraphQLFragmentPath {
var _fragment: FragmentPath<UnderlyingType> {
return self
}
}
extension GraphQLFragmentPath {
func _forEach<Value, Output>(_: KeyPath<GraphQLFragmentPath<TargetType, Value>, GraphQLPath<TargetType, Output>>) -> GraphQLPath<TargetType, [Output]> where UnderlyingType == [Value] {
return .init()
}
func _forEach<Value, Output>(_: KeyPath<GraphQLFragmentPath<TargetType, Value>, GraphQLPath<TargetType, Output>>) -> GraphQLPath<TargetType, [Output]?> where UnderlyingType == [Value]? {
return .init()
}
}
extension GraphQLFragmentPath {
func _forEach<Value, Output>(_: KeyPath<GraphQLFragmentPath<TargetType, Value>, GraphQLFragmentPath<TargetType, Output>>) -> GraphQLFragmentPath<TargetType, [Output]> where UnderlyingType == [Value] {
return .init()
}
func _forEach<Value, Output>(_: KeyPath<GraphQLFragmentPath<TargetType, Value>, GraphQLFragmentPath<TargetType, Output>>) -> GraphQLFragmentPath<TargetType, [Output]?> where UnderlyingType == [Value]? {
return .init()
}
}
extension GraphQLFragmentPath {
func _flatten<T>() -> GraphQLFragmentPath<TargetType, [T]> where UnderlyingType == [[T]] {
return .init()
}
func _flatten<T>() -> GraphQLFragmentPath<TargetType, [T]?> where UnderlyingType == [[T]]? {
return .init()
}
}
extension GraphQLPath {
func _flatten<T>() -> GraphQLPath<TargetType, [T]> where Value == [[T]] {
return .init()
}
func _flatten<T>() -> GraphQLPath<TargetType, [T]?> where Value == [[T]]? {
return .init()
}
}
extension GraphQLFragmentPath {
func _compactMap<T>() -> GraphQLFragmentPath<TargetType, [T]> where UnderlyingType == [T?] {
return .init()
}
func _compactMap<T>() -> GraphQLFragmentPath<TargetType, [T]?> where UnderlyingType == [T?]? {
return .init()
}
}
extension GraphQLPath {
func _compactMap<T>() -> GraphQLPath<TargetType, [T]> where Value == [T?] {
return .init()
}
func _compactMap<T>() -> GraphQLPath<TargetType, [T]?> where Value == [T?]? {
return .init()
}
}
extension GraphQLFragmentPath {
func _nonNull<T>() -> GraphQLFragmentPath<TargetType, T> where UnderlyingType == T? {
return .init()
}
}
extension GraphQLPath {
func _nonNull<T>() -> GraphQLPath<TargetType, T> where Value == T? {
return .init()
}
}
extension GraphQLFragmentPath {
func _withDefault<T>(_: @autoclosure () -> T) -> GraphQLFragmentPath<TargetType, T> where UnderlyingType == T? {
return .init()
}
}
extension GraphQLPath {
func _withDefault<T>(_: @autoclosure () -> T) -> GraphQLPath<TargetType, T> where Value == T? {
return .init()
}
}
// MARK: - Basic API: Arguments
enum GraphQLArgument<Value> {
enum QueryArgument {
case withDefault(Value)
case forced
}
case value(Value)
case argument(QueryArgument)
}
extension GraphQLArgument {
static var argument: GraphQLArgument<Value> {
return .argument(.forced)
}
static func argument(default value: Value) -> GraphQLArgument<Value> {
return .argument(.withDefault(value))
}
}
// MARK: - Basic API: Paging
class Paging<Value: Fragment>: DynamicProperty, ObservableObject {
fileprivate struct Response {
let values: [Value]
let cursor: String?
let hasMore: Bool
static var empty: Response {
Response(values: [], cursor: nil, hasMore: false)
}
}
fileprivate typealias Completion = (Result<Response, Error>) -> Void
fileprivate typealias Loader = (String, Int?, @escaping Completion) -> Void
private let loader: Loader
@Published
private(set) var isLoading: Bool = false
@Published
private(set) var values: [Value] = []
private var cursor: String?
@Published
private(set) var hasMore: Bool = false
@Published
private(set) var error: Error? = nil
fileprivate init(_ response: Response, loader: @escaping Loader) {
self.loader = loader
use(response)
}
func loadMore(pageSize: Int? = nil) {
guard let cursor = cursor, !isLoading else { return }
isLoading = true
loader(cursor, pageSize) { [weak self] result in
switch result {
case let .success(response):
self?.use(response)
case let .failure(error):
self?.handle(error)
}
}
}
private func use(_ response: Response) {
isLoading = false
values += response.values
cursor = response.cursor
hasMore = response.hasMore
}
private func handle(_ error: Error) {
isLoading = false
hasMore = false
self.error = error
}
}
// MARK: - Basic API: Error Types
enum GraphQLLoadingError<T: API>: Error {
case emptyData(api: T)
case graphQLErrors([GraphQLError])
case networkError(Error)
}
// MARK: - Basic API: Refresh
protocol QueryRefreshController {
func refresh()
func refresh(completion: @escaping (Error?) -> Void)
}
private struct QueryRefreshControllerEnvironmentKey: EnvironmentKey {
static let defaultValue: QueryRefreshController? = nil
}
extension EnvironmentValues {
var queryRefreshController: QueryRefreshController? {
get {
self[QueryRefreshControllerEnvironmentKey.self]
} set {
self[QueryRefreshControllerEnvironmentKey.self] = newValue
}
}
}
// MARK: - Error Handling
enum QueryError {
case network(Error)
case graphql([GraphQLError])
}
extension QueryError: CustomStringConvertible {
var description: String {
switch self {
case let .network(error):
return error.localizedDescription
case let .graphql(errors):
return errors.map { $0.description }.joined(separator: ", ")
}
}
}
extension QueryError {
var networkError: Error? {
guard case let .network(error) = self else { return nil }
return error
}
var graphQLErrors: [GraphQLError]? {
guard case let .graphql(errors) = self else { return nil }
return errors
}
}
protocol QueryErrorController {
var error: QueryError? { get }
func clear()
}
private struct QueryErrorControllerEnvironmentKey: EnvironmentKey {
static let defaultValue: QueryErrorController? = nil
}
extension EnvironmentValues {
var queryErrorController: QueryErrorController? {
get {
self[QueryErrorControllerEnvironmentKey.self]
} set {
self[QueryErrorControllerEnvironmentKey.self] = newValue
}
}
}
// MARK: - Basic API: Views
private struct QueryRenderer<Query: GraphQLQuery, Loading: View, Error: View, Content: View>: View {
typealias ContentFactory = (Query.Data) -> Content
typealias ErrorFactory = (QueryError) -> Error
private final class ViewModel: ObservableObject {
@Published var isLoading: Bool = false
@Published var value: Query.Data? = nil
@Published var error: QueryError? = nil
private var previous: Query?
private var cancellable: Apollo.Cancellable?
deinit {
cancel()
}
func load(client: ApolloClient, query: Query) {
guard previous !== query || (value == nil && !isLoading) else { return }
perform(client: client, query: query)
}
func refresh(client: ApolloClient, query: Query, completion: ((Swift.Error?) -> Void)? = nil) {
perform(client: client, query: query, cachePolicy: .fetchIgnoringCacheData, completion: completion)
}
private func perform(client: ApolloClient, query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, completion: ((Swift.Error?) -> Void)? = nil) {
previous = query
cancellable = client.fetch(query: query, cachePolicy: cachePolicy) { [weak self] result in
defer {
self?.cancellable = nil
self?.isLoading = false
}
switch result {
case let .success(result):
self?.value = result.data
self?.error = result.errors.map { .graphql($0) }
completion?(nil)
case let .failure(error):
self?.error = .network(error)
completion?(error)
}
}
isLoading = true
}
func cancel() {
cancellable?.cancel()
}
}
private struct RefreshController: QueryRefreshController {
let client: ApolloClient
let query: Query
let viewModel: ViewModel
func refresh() {
viewModel.refresh(client: client, query: query)
}
func refresh(completion: @escaping (Swift.Error?) -> Void) {
viewModel.refresh(client: client, query: query, completion: completion)
}
}
private struct ErrorController: QueryErrorController {
let viewModel: ViewModel
var error: QueryError? {
return viewModel.error
}
func clear() {
viewModel.error = nil
}
}
let client: ApolloClient
let query: Query
let loading: Loading
let error: ErrorFactory
let factory: ContentFactory
@ObservedObject private var viewModel = ViewModel()
@State private var hasAppeared = false
var body: some View {
if hasAppeared {
self.viewModel.load(client: self.client, query: self.query)
}
return VStack {
viewModel.isLoading && viewModel.value == nil && viewModel.error == nil ? loading : nil
viewModel.value == nil ? viewModel.error.map(error) : nil
viewModel
.value
.map(factory)
.environment(\.queryRefreshController, RefreshController(client: client, query: query, viewModel: viewModel))
.environment(\.queryErrorController, ErrorController(viewModel: viewModel))
}
.onAppear {
DispatchQueue.main.async {
self.hasAppeared = true
}
self.viewModel.load(client: self.client, query: self.query)
}
.onDisappear {
DispatchQueue.main.async {
self.hasAppeared = false
}
self.viewModel.cancel()
}
}
}
private struct BasicErrorView: View {
let error: QueryError
var body: some View {
Text("Error: \(error.description)")
}
}
private struct BasicLoadingView: View {
var body: some View {
Text("Loading")
}
}
struct PagingView<Value: Fragment>: View {
enum Mode {
case list
case vertical(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, insets: EdgeInsets = EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
case horizontal(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, insets: EdgeInsets = EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
enum Data {
case item(Value, Int)
case loading
case error(Error)
fileprivate var id: String {
switch self {
case let .item(_, int):
return int.description
case .error:
return "error"
case .loading:
return "loading"
}
}
}
@ObservedObject private var paging: Paging<Value>
private let mode: Mode
private let pageSize: Int?
private var loader: (Data) -> AnyView
@State private var visibleRect: CGRect = .zero
init(_ paging: Paging<Value>, mode: Mode = .list, pageSize: Int? = nil, loader: @escaping (Data) -> AnyView) {
self.paging = paging
self.mode = mode
self.pageSize = pageSize
self.loader = loader
}
var body: some View {
let data = self.paging.values.enumerated().map { Data.item($0.element, $0.offset) } +
[self.paging.isLoading ? Data.loading : nil, self.paging.error.map(Data.error)].compactMap { $0 }
switch mode {
case .list:
return AnyView(
List(data, id: \.id) { data in
self.loader(data).onAppear { self.onAppear(data: data) }
}
)
case let .vertical(alignment, spacing, insets):
return AnyView(
ScrollView(.horizontal, showsIndicators: false) {
VStack(alignment: alignment, spacing: spacing) {
ForEach(data, id: \.id) { data in
self.loader(data).ifVisible(in: self.visibleRect, in: .named("InfiniteVerticalScroll")) { self.onAppear(data: data) }
}
}
.padding(insets)
}
.coordinateSpace(name: "InfiniteVerticalScroll")
.rectReader($visibleRect, in: .named("InfiniteVerticalScroll"))
)
case let .horizontal(alignment, spacing, insets):
return AnyView(
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: alignment, spacing: spacing) {
ForEach(data, id: \.id) { data in
self.loader(data).ifVisible(in: self.visibleRect, in: .named("InfiniteHorizontalScroll")) { self.onAppear(data: data) }
}
}
.padding(insets)
}
.coordinateSpace(name: "InfiniteHorizontalScroll")
.rectReader($visibleRect, in: .named("InfiniteHorizontalScroll"))
)
}
}
private func onAppear(data: Data) {
guard !paging.isLoading,
paging.hasMore,
case let .item(_, index) = data,
index > paging.values.count - 2 else { return }
DispatchQueue.main.async {
paging.loadMore(pageSize: pageSize)
}
}
}
extension PagingView {
init<Loading: View, Error: View, Data: View>(_ paging: Paging<Value>,
mode: Mode = .list,
pageSize: Int? = nil,
loading loadingView: @escaping () -> Loading,
error errorView: @escaping (Swift.Error) -> Error,
item itemView: @escaping (Value) -> Data) {
self.init(paging, mode: mode, pageSize: pageSize) { data in
switch data {
case let .item(item, _):
return AnyView(itemView(item))
case let .error(error):
return AnyView(errorView(error))
case .loading:
return AnyView(loadingView())
}
}
}
init<Error: View, Data: View>(_ paging: Paging<Value>,
mode: Mode = .list,
pageSize: Int? = nil,
error errorView: @escaping (Swift.Error) -> Error,
item itemView: @escaping (Value) -> Data) {
self.init(paging,
mode: mode,
pageSize: pageSize,
loading: { PagingBasicLoadingView(content: itemView) },
error: errorView,
item: itemView)
}
init<Loading: View, Data: View>(_ paging: Paging<Value>,
mode: Mode = .list,
pageSize: Int? = nil,
loading loadingView: @escaping () -> Loading,
item itemView: @escaping (Value) -> Data) {
self.init(paging,
mode: mode,
pageSize: pageSize,
loading: loadingView,
error: { Text("Error: \($0.localizedDescription)") },
item: itemView)
}
init<Data: View>(_ paging: Paging<Value>,
mode: Mode = .list,
pageSize: Int? = nil,
item itemView: @escaping (Value) -> Data) {
self.init(paging,
mode: mode,
pageSize: pageSize,
loading: { PagingBasicLoadingView(content: itemView) },
error: { Text("Error: \($0.localizedDescription)") },
item: itemView)
}
}
private struct PagingBasicLoadingView<Value: Fragment, Content: View>: View {
let content: (Value) -> Content
var body: some View {
if #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) {
content(.placeholder).disabled(true).redacted(reason: .placeholder)
} else {
BasicLoadingView()
}
}
}
extension PagingView.Mode {
static func vertical(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, padding edges: Edge.Set, by padding: CGFloat) -> PagingView.Mode {
return .vertical(alignment: alignment,
spacing: spacing,
insets: EdgeInsets(top: edges.contains(.top) ? padding : 0,
leading: edges.contains(.leading) ? padding : 0,
bottom: edges.contains(.bottom) ? padding : 0,
trailing: edges.contains(.trailing) ? padding : 0))
}
static func vertical(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, padding: CGFloat) -> PagingView.Mode {
return .vertical(alignment: alignment, spacing: spacing, padding: .all, by: padding)
}
static var vertical: PagingView.Mode { .vertical() }
static func horizontal(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, padding edges: Edge.Set, by padding: CGFloat) -> PagingView.Mode {
return .horizontal(alignment: alignment,
spacing: spacing,
insets: EdgeInsets(top: edges.contains(.top) ? padding : 0,
leading: edges.contains(.leading) ? padding : 0,
bottom: edges.contains(.bottom) ? padding : 0,
trailing: edges.contains(.trailing) ? padding : 0))
}
static func horizontal(alignment: VerticalAlignment = .center, spacing: CGFloat? = nil, padding: CGFloat) -> PagingView.Mode {
return .horizontal(alignment: alignment, spacing: spacing, padding: .all, by: padding)
}
static var horizontal: PagingView.Mode { .horizontal() }
}
extension View {
fileprivate func rectReader(_ binding: Binding<CGRect>, in space: CoordinateSpace) -> some View {
background(GeometryReader { (geometry) -> AnyView in
let rect = geometry.frame(in: space)
DispatchQueue.main.async {
binding.wrappedValue = rect
}
return AnyView(Rectangle().fill(Color.clear))
})
}
}
extension View {
fileprivate func ifVisible(in rect: CGRect, in space: CoordinateSpace, execute: @escaping () -> Void) -> some View {
background(GeometryReader { (geometry) -> AnyView in
let frame = geometry.frame(in: space)
if frame.intersects(rect) {
execute()
}
return AnyView(Rectangle().fill(Color.clear))
})
}
}
// MARK: - Basic API: Decoders
protocol GraphQLValueDecoder {
associatedtype Encoded
associatedtype Decoded
static func decode(encoded: Encoded) throws -> Decoded
}
enum NoOpDecoder<T>: GraphQLValueDecoder {
static func decode(encoded: T) throws -> T {
return encoded
}
}
// MARK: - Basic API: Scalar Handling
protocol GraphQLScalar {
associatedtype Scalar
static var placeholder: Self { get }
init(from scalar: Scalar) throws
}
extension Array: GraphQLScalar where Element: GraphQLScalar {
static var placeholder: [Element] {
return Array(repeating: Element.placeholder, count: 5)
}
init(from scalar: [Element.Scalar]) throws {
self = try scalar.map { try Element(from: $0) }
}
}
extension Optional: GraphQLScalar where Wrapped: GraphQLScalar {
static var placeholder: Wrapped? {
return Wrapped.placeholder
}
init(from scalar: Wrapped.Scalar?) throws {
guard let scalar = scalar else {
self = .none
return
}
self = .some(try Wrapped(from: scalar))
}
}
extension URL: GraphQLScalar {
typealias Scalar = String
static let placeholder: URL = URL(string: "https://graphaello.dev/assets/logo.png")!
private struct URLScalarDecodingError: Error {
let string: String
}
init(from string: Scalar) throws {
guard let url = URL(string: string) else {
throw URLScalarDecodingError(string: string)
}
self = url
}
}
enum ScalarDecoder<ScalarType: GraphQLScalar>: GraphQLValueDecoder {
typealias Encoded = ScalarType.Scalar
typealias Decoded = ScalarType
static func decode(encoded: ScalarType.Scalar) throws -> ScalarType {
if let encoded = encoded as? String, encoded == "__GRAPHAELLO_PLACEHOLDER__" {
return Decoded.placeholder
}
return try ScalarType(from: encoded)
}
}
// MARK: - Basic API: HACK - AnyObservableObject
private class AnyObservableObject: ObservableObject {
let objectWillChange = ObservableObjectPublisher()
var cancellable: AnyCancellable?
func use<O: ObservableObject>(_ object: O) {
cancellable?.cancel()
cancellable = object.objectWillChange.sink { [unowned self] _ in self.objectWillChange.send() }
}
}
// MARK: - Basic API: Graph QL Property Wrapper
@propertyWrapper
struct GraphQL<Decoder: GraphQLValueDecoder>: DynamicProperty {
private let initialValue: Decoder.Decoded
@State
private var value: Decoder.Decoded? = nil
@ObservedObject
private var observed: AnyObservableObject = AnyObservableObject()
private let updateObserved: ((Decoder.Decoded) -> Void)?
var wrappedValue: Decoder.Decoded {
get {
return value ?? initialValue
}
nonmutating set {
value = newValue
updateObserved?(newValue)
}
}
var projectedValue: Binding<Decoder.Decoded> {
return Binding(get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue })
}
init<T: Target>(_: @autoclosure () -> GraphQLPath<T, Decoder.Encoded>) {
fatalError("Initializer with path only should never be used")
}
init<T: Target, Value>(_: @autoclosure () -> GraphQLPath<T, Value>) where Decoder == NoOpDecoder<Value> {
fatalError("Initializer with path only should never be used")
}
init<T: Target, Value: GraphQLScalar>(_: @autoclosure () -> GraphQLPath<T, Value.Scalar>) where Decoder == ScalarDecoder<Value> {
fatalError("Initializer with path only should never be used")
}
fileprivate init(_ wrappedValue: Decoder.Encoded) {
initialValue = try! Decoder.decode(encoded: wrappedValue)
updateObserved = nil
}
mutating func update() {
_value.update()
_observed.update()
}
}
extension GraphQL where Decoder.Decoded: ObservableObject {
fileprivate init(_ wrappedValue: Decoder.Encoded) {
let value = try! Decoder.decode(encoded: wrappedValue)
initialValue = value
let observed = AnyObservableObject()
observed.use(value)
self.observed = observed
updateObserved = { observed.use($0) }
}
}
extension GraphQL {
init<T: Target, Value: Fragment>(_: @autoclosure () -> GraphQLFragmentPath<T, Value.UnderlyingType>) where Decoder == NoOpDecoder<Value> {
fatalError("Initializer with path only should never be used")
}
}
extension GraphQL {
init<T: API, C: Connection, F: Fragment>(_: @autoclosure () -> GraphQLFragmentPath<T, C>) where Decoder == NoOpDecoder<Paging<F>>, C.Node == F.UnderlyingType {
fatalError("Initializer with path only should never be used")
}
init<T: API, C: Connection, F: Fragment>(_: @autoclosure () -> GraphQLFragmentPath<T, C?>) where Decoder == NoOpDecoder<Paging<F>?>, C.Node == F.UnderlyingType {
fatalError("Initializer with path only should never be used")
}
}
extension GraphQL {
init<T: MutationTarget, MutationType: Mutation>(_: @autoclosure () -> GraphQLPath<T, MutationType.Value>) where Decoder == NoOpDecoder<MutationType> {
fatalError("Initializer with path only should never be used")
}
init<T: MutationTarget, MutationType: Mutation>(_: @autoclosure () -> GraphQLFragmentPath<T, MutationType.Value.UnderlyingType>) where Decoder == NoOpDecoder<MutationType>, MutationType.Value: Fragment {
fatalError("Initializer with path only should never be used")
}
}
extension GraphQL {
init<T: Target, M: MutationTarget, MutationType: CurrentValueMutation>(_: @autoclosure () -> GraphQLPath<T, MutationType.Value>, mutation _: @autoclosure () -> GraphQLPath<M, MutationType.Value>) where Decoder == NoOpDecoder<MutationType> {
fatalError("Initializer with path only should never be used")
}
init<T: Target, M: MutationTarget, MutationType: CurrentValueMutation>(_: @autoclosure () -> GraphQLFragmentPath<T, MutationType.Value.UnderlyingType>, mutation _: @autoclosure () -> GraphQLFragmentPath<M, MutationType.Value.UnderlyingType>) where Decoder == NoOpDecoder<MutationType>, MutationType.Value: Fragment {
fatalError("Initializer with path only should never be used")
}
}
// MARK: - Covid
#if GRAPHAELLO_COVID_UI_TARGET
struct Covid: API {
let client: ApolloClient
typealias Query = Covid
typealias Path<V> = GraphQLPath<Covid, V>
typealias FragmentPath<V> = GraphQLFragmentPath<Covid, V>
static func continent(identifier _: GraphQLArgument<Covid.ContinentIdentifier> = .argument) -> FragmentPath<Covid.DetailedContinent> {
return .init()
}
static var continent: FragmentPath<Covid.DetailedContinent> { .init() }
static var continents: FragmentPath<[Covid.IContinent]> { .init() }
static func countries(after _: GraphQLArgument<String?> = .argument,
before _: GraphQLArgument<String?> = .argument,
first _: GraphQLArgument<Int?> = .argument,
last _: GraphQLArgument<Int?> = .argument) -> FragmentPath<Covid.CountryConnection> {
return .init()
}
static var countries: FragmentPath<Covid.CountryConnection> { .init() }
static func country(identifier _: GraphQLArgument<Covid.CountryIdentifier> = .argument) -> FragmentPath<Covid.Country> {
return .init()
}
static var country: FragmentPath<Covid.Country> { .init() }
static func historicalData(after _: GraphQLArgument<String?> = .argument,
before _: GraphQLArgument<String?> = .argument,
first _: GraphQLArgument<Int?> = .argument,
last _: GraphQLArgument<Int?> = .argument) -> FragmentPath<Covid.HistoricalDataConnection> {
return .init()
}
static var historicalData: FragmentPath<Covid.HistoricalDataConnection> { .init() }
static var myCountry: FragmentPath<Covid.Country?> { .init() }
static var world: FragmentPath<Covid.World> { .init() }
enum Affected: Target {
typealias Path<V> = GraphQLPath<Affected, V>
typealias FragmentPath<V> = GraphQLFragmentPath<Affected, V>
static var active: Path<Int> { .init() }
static var cases: Path<Int> { .init() }
static var critical: Path<Int> { .init() }
static var deaths: Path<Int> { .init() }
static var recovered: Path<Int> { .init() }
static var todayCases: Path<Int> { .init() }
static var todayDeaths: Path<Int> { .init() }
static var updated: Path<String> { .init() }
static var iAffected: FragmentPath<IAffected> { .init() }
static var _fragment: FragmentPath<Affected> { .init() }
}
enum Continent: Target {
typealias Path<V> = GraphQLPath<Continent, V>
typealias FragmentPath<V> = GraphQLFragmentPath<Continent, V>
static var active: Path<Int> { .init() }
static var cases: Path<Int> { .init() }
static var critical: Path<Int> { .init() }
static var deaths: Path<Int> { .init() }
static var details: FragmentPath<Covid.DetailedContinent> { .init() }
static var identifier: Path<Covid.ContinentIdentifier> { .init() }
static var name: Path<String> { .init() }
static var recovered: Path<Int> { .init() }
static var todayCases: Path<Int> { .init() }
static var todayDeaths: Path<Int> { .init() }
static var updated: Path<String> { .init() }
static var iAffected: FragmentPath<IAffected> { .init() }
static var iContinent: FragmentPath<IContinent> { .init() }
static var _fragment: FragmentPath<Continent> { .init() }
}
enum ContinentIdentifier: String, Target {
typealias Path<V> = GraphQLPath<ContinentIdentifier, V>
typealias FragmentPath<V> = GraphQLFragmentPath<ContinentIdentifier, V>
case northAmerica = "NorthAmerica"
case southAmerica = "SouthAmerica"
case europe = "Europe"
case asia = "Asia"
case australiaOceania = "AustraliaOceania"
case africa = "Africa"
static var _fragment: FragmentPath<ContinentIdentifier> { .init() }