This repository has been archived by the owner on Feb 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
vue-relay.esm.js
1284 lines (1133 loc) · 47.2 KB
/
vue-relay.esm.js
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
/**
* vue-relay v1.5.3
* (c) 2018 なつき
* @license BSD-2-Clause
*/
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var invariant = require('fbjs/lib/invariant');
var VueRelayQueryFetcher = function () {
function VueRelayQueryFetcher() {
classCallCheck(this, VueRelayQueryFetcher);
// this._fetchOptions
// this._pendingRequest
// this._rootSubscription
this._selectionReferences = [];
// this._snapshot
// this._cacheSelectionReference
}
createClass(VueRelayQueryFetcher, [{
key: 'lookupInStore',
value: function lookupInStore(environment, operation) {
if (environment.check(operation.root)) {
this._retainCachedOperation(environment, operation);
return environment.lookup(operation.fragment);
}
return null;
}
}, {
key: 'execute',
value: function execute(_ref) {
var _this = this;
var environment = _ref.environment,
operation = _ref.operation,
cacheConfig = _ref.cacheConfig,
_ref$preservePrevious = _ref.preservePreviousReferences,
preservePreviousReferences = _ref$preservePrevious === undefined ? false : _ref$preservePrevious;
var createOperationSelector = environment.unstable_internal.createOperationSelector;
var nextReferences = [];
return environment.execute({ operation: operation, cacheConfig: cacheConfig }).map(function (payload) {
var operationForPayload = createOperationSelector(operation.node, payload.variables, payload.operation);
nextReferences.push(environment.retain(operationForPayload.root));
return payload;
}).do({
error: function error() {
// We may have partially fulfilled the request, so let the next request
// or the unmount dispose of the references.
_this._selectionReferences = _this._selectionReferences.concat(nextReferences);
},
complete: function complete() {
if (!preservePreviousReferences) {
_this._disposeSelectionReferences();
}
_this._selectionReferences = _this._selectionReferences.concat(nextReferences);
},
unsubscribe: function unsubscribe() {
// Let the next request or the unmount code dispose of the references.
// We may have partially fulfilled the request.
_this._selectionReferences = _this._selectionReferences.concat(nextReferences);
}
});
}
/**
* `fetch` fetches the data for the given operation.
* If a result is immediately available synchronously, it will be synchronously
* returned by this function.
*
* Otherwise, the fetched result will be communicated via the `onDataChange` callback.
* `onDataChange` will be called with the first result (**if it wasn't returned synchronously**),
* and then subsequently whenever the data changes.
*/
}, {
key: 'fetch',
value: function fetch(fetchOptions) {
var _this2 = this;
var cacheConfig = fetchOptions.cacheConfig,
environment = fetchOptions.environment,
onDataChange = fetchOptions.onDataChange,
operation = fetchOptions.operation;
var fetchHasReturned = false;
var _error = void 0;
this._disposeRequest();
this._fetchOptions = fetchOptions;
var request = this.execute({
environment: environment,
operation: operation,
cacheConfig: cacheConfig
}).finally(function () {
_this2._pendingRequest = null;
}).subscribe({
next: function next() {
// Only notify of the first result if `next` is being called **asynchronously**
// (i.e. after `fetch` has returned).
_this2._onQueryDataAvailable({ notifyFirstResult: fetchHasReturned });
},
error: function error(err) {
// Only notify of error if `error` is being called **asynchronously**
// (i.e. after `fetch` has returned).
if (fetchHasReturned) {
onDataChange({ error: err });
} else {
_error = err;
}
}
});
this._pendingRequest = {
dispose: function dispose() {
request.unsubscribe();
}
};
fetchHasReturned = true;
if (_error) {
throw _error;
}
return this._snapshot;
}
}, {
key: 'retry',
value: function retry() {
invariant(this._fetchOptions, 'RelayQueryFetcher: `retry` should be called after having called `fetch`');
return this.fetch(this._fetchOptions);
}
}, {
key: 'dispose',
value: function dispose() {
this._disposeRequest();
this._disposeSelectionReferences();
}
}, {
key: '_disposeRequest',
value: function _disposeRequest() {
this._snapshot = null;
// order is important, dispose of pendingFetch before selectionReferences
if (this._pendingRequest) {
this._pendingRequest.dispose();
}
if (this._rootSubscription) {
this._rootSubscription.dispose();
this._rootSubscription = null;
}
}
}, {
key: '_retainCachedOperation',
value: function _retainCachedOperation(environment, operation) {
this._disposeCacheSelectionReference();
this._cacheSelectionReference = environment.retain(operation.root);
}
}, {
key: '_disposeCacheSelectionReference',
value: function _disposeCacheSelectionReference() {
this._cacheSelectionReference && this._cacheSelectionReference.dispose();
this._cacheSelectionReference = null;
}
}, {
key: '_disposeSelectionReferences',
value: function _disposeSelectionReferences() {
this._disposeCacheSelectionReference();
this._selectionReferences.forEach(function (r) {
return r.dispose();
});
this._selectionReferences = [];
}
}, {
key: '_onQueryDataAvailable',
value: function _onQueryDataAvailable(_ref2) {
var notifyFirstResult = _ref2.notifyFirstResult;
invariant(this._fetchOptions, 'RelayQueryFetcher: `_onQueryDataAvailable` should have been called after having called `fetch`');
var _fetchOptions = this._fetchOptions,
environment = _fetchOptions.environment,
onDataChange = _fetchOptions.onDataChange,
operation = _fetchOptions.operation;
// `_onQueryDataAvailable` can be called synchronously the first time and can be called
// multiple times by network layers that support data subscriptions.
// Wait until the first payload to call `onDataChange` and subscribe for data updates.
if (this._snapshot) {
return;
}
this._snapshot = environment.lookup(operation.fragment);
// Subscribe to changes in the data of the root fragment
this._rootSubscription = environment.subscribe(this._snapshot, function (snapshot) {
return onDataChange({ snapshot: snapshot });
});
if (this._snapshot && notifyFirstResult) {
onDataChange({ snapshot: this._snapshot });
}
}
}]);
return VueRelayQueryFetcher;
}();
var areEqual = require('fbjs/lib/areEqual');
var STORE_THEN_NETWORK = 'STORE_THEN_NETWORK';
var getLoadingRenderProps = function getLoadingRenderProps() {
return {
error: null,
props: null, // `props: null` indicates that the data is being fetched (i.e. loading)
retry: null
};
};
var getEmptyRenderProps = function getEmptyRenderProps(_) {
return {
error: null,
props: {}, // `props: {}` indicates no data available
retry: null
};
};
var getRenderProps = function getRenderProps(error, snapshot, queryFetcher, retryCallbacks) {
return {
error: error,
props: snapshot ? snapshot.data : null,
retry: function retry() {
var syncSnapshot = queryFetcher.retry();
if (syncSnapshot) {
retryCallbacks.handleDataChange({ snapshot: syncSnapshot });
} else if (error) {
// If retrying after an error and no synchronous result available,
// reset the render props
retryCallbacks.handleRetryAfterError(error);
}
}
};
};
var fetchQueryAndComputeStateFromProps = function fetchQueryAndComputeStateFromProps(props, queryFetcher, retryCallbacks) {
var environment = props.environment,
query = props.query,
variables = props.variables;
if (query) {
var genericEnvironment = environment;
var _genericEnvironment$u = genericEnvironment.unstable_internal,
createOperationSelector = _genericEnvironment$u.createOperationSelector,
getRequest = _genericEnvironment$u.getRequest;
var request = getRequest(query);
var operation = createOperationSelector(request, variables);
try {
var storeSnapshot = props.dataFrom === STORE_THEN_NETWORK ? queryFetcher.lookupInStore(genericEnvironment, operation) : null;
var querySnapshot = queryFetcher.fetch({
cacheConfig: props.cacheConfig,
dataFrom: props.dataFrom,
environment: genericEnvironment,
onDataChange: retryCallbacks.handleDataChange,
operation: operation
});
// Use network data first, since it may be fresher
var snapshot = querySnapshot || storeSnapshot;
if (!snapshot) {
return {
relayContextEnvironment: environment,
relayContextVariables: operation.variables,
renderProps: getLoadingRenderProps()
};
}
return {
relayContextEnvironment: environment,
relayContextVariables: operation.variables,
renderProps: getRenderProps(null, snapshot, queryFetcher, retryCallbacks)
};
} catch (error) {
return {
relayContextEnvironment: environment,
relayContextVariables: operation.variables,
renderProps: getRenderProps(error, null, queryFetcher, retryCallbacks)
};
}
} else {
queryFetcher.dispose();
return {
relayContextEnvironment: environment,
relayContextVariables: variables,
renderProps: getEmptyRenderProps()
};
}
};
var props = {
cacheConfig: {},
dataFrom: {},
environment: {
required: true
},
query: {},
variables: {
type: Object,
default: function _default() {
return {};
}
}
};
var QueryRenderer = {
name: 'relay-query-renderer',
props: props,
data: function data() {
var _this = this;
var handleDataChange = function handleDataChange(_ref) {
var error = _ref.error,
snapshot = _ref.snapshot;
_this.setState({ renderProps: getRenderProps(error, snapshot, queryFetcher, retryCallbacks) });
};
var handleRetryAfterError = function handleRetryAfterError(_) {
_this.setState({ renderProps: getLoadingRenderProps() });
};
var retryCallbacks = {
handleDataChange: handleDataChange,
handleRetryAfterError: handleRetryAfterError
};
var queryFetcher = new VueRelayQueryFetcher();
var state = fetchQueryAndComputeStateFromProps(this.$props, queryFetcher, retryCallbacks);
return {
// React's getChildContext() is dynamically resolved,
// Vue does not have this feature, instead, we `inject` a static reference.
// `context` is frozen to prevent reference changes to `context.relay`.
// `context.relay` itself is not frozen and should be updated accordingly.
context: Object.freeze({
relay: {
environment: state.relayContextEnvironment,
variables: state.relayContextVariables
}
}),
state: Object.freeze(_extends({
prevPropsEnvironment: this.environment,
prevPropsVariables: this.variables,
prevQuery: this.query,
queryFetcher: queryFetcher,
retryCallbacks: retryCallbacks
}, state))
};
},
methods: {
setState: function setState(state) {
this.state = Object.freeze(_extends({}, this.state, state));
}
},
watch: _extends({}, Object.keys(props).map(function (key) {
return defineProperty({}, key, function () {
if (this.state.prevQuery !== this.query || this.state.prevPropsEnvironment !== this.environment || !areEqual(this.state.prevPropsVariables, this.variables)) {
var state = fetchQueryAndComputeStateFromProps(this.$props, this.state.queryFetcher, this.state.retryCallbacks);
// React getDerivedStateFromProps is static method.
// Vue beforeUpdate is instance method.
// Thus updaing relayContext here instead of in render.
this.context.relay.environment = state.relayContextEnvironment;
this.context.relay.variables = state.relayContextVariables;
this.setState(_extends({
prevQuery: this.query,
prevPropsEnvironment: this.environment,
prevPropsVariables: this.variables
}, state));
}
});
})),
render: function render(h) {
if (process.env.NODE_ENV !== 'production') {
require('relay-runtime/lib/deepFreeze')(this.state.renderProps);
}
return h(this.component);
},
created: function created() {
var _this2 = this;
this.component = {
name: 'relay-context-provider',
provide: {
relay: this.context.relay
},
render: function render(h) {
return h('keep-alive', {
props: {
include: []
}
}, _this2.$scopedSlots.default(_this2.state.renderProps));
}
};
},
beforeDestroy: function beforeDestroy() {
this.state.queryFetcher.dispose();
}
};
var isRelayEnvironment = function isRelayEnvironment(environment) {
return (typeof environment === 'undefined' ? 'undefined' : _typeof(environment)) === 'object' && environment !== null && typeof environment.applyMutation === 'function' && typeof environment.check === 'function' && typeof environment.check === 'function' && typeof environment.lookup === 'function' && typeof environment.retain === 'function' && typeof environment.sendMutation === 'function' && typeof environment.sendQuery === 'function' && typeof environment.execute === 'function' && typeof environment.subscribe === 'function';
};
var isRelayVariables = function isRelayVariables(variables) {
return (typeof variables === 'undefined' ? 'undefined' : _typeof(variables)) === 'object' && variables !== null && !Array.isArray(variables);
};
var isRelayContext = function isRelayContext(context) {
return (typeof context === 'undefined' ? 'undefined' : _typeof(context)) === 'object' && context !== null && !Array.isArray(context) && isRelayEnvironment(context.environment) && isRelayVariables(context.variables);
};
var invariant$1 = require('fbjs/lib/invariant');
var mapObject = require('fbjs/lib/mapObject');
var assertRelayContext = function assertRelayContext(relay) {
invariant$1(isRelayContext(relay), 'RelayContextConsumer: Expected `relayContext` to be an object ' + 'conforming to the `RelayContext` interface, got `%s`.', relay);
return relay;
};
var buildVueRelayContainer = function buildVueRelayContainer(component, fragmentSpec, createContainerWithFragments) {
return {
name: 'relay-context-consumer',
inject: ['relay'],
render: function render(h) {
return h(this.component, {
props: this.$attrs
});
},
created: function created() {
var relay = assertRelayContext(this.relay);
var getFragmentFromTag = relay.environment.unstable_internal.getFragment;
var fragments = mapObject(fragmentSpec, getFragmentFromTag);
var context = this;
this.component = {
extends: createContainerWithFragments.call(this, fragments),
props: Object.keys(fragments),
render: function render(h) {
if (this.context) {
return h(this.component);
}
return this.component.render(h);
},
created: function created() {
var _this = this;
this.component = {
name: 'relay-context-provider',
provide: {
relay: (this.context || context).relay
},
render: function render(h) {
if (component != null) {
return h(component, {
props: _extends({}, _this.$attrs, _this.state.data, {
relay: _this.state.relayProp
})
});
}
return h('keep-alive', {
props: {
include: []
}
}, context.$scopedSlots.default(_extends({}, _this.state.data, {
relay: _this.state.relayProp
})));
}
};
}
};
}
};
};
var areEqual$1 = require('fbjs/lib/areEqual');
var invariant$2 = require('fbjs/lib/invariant');
var _require = require('relay-runtime'),
Observable = _require.Observable;
var createContainerWithFragments = function createContainerWithFragments(fragments, taggedNode) {
var relay = this.relay;
return {
name: 'relay-refetch-container',
data: function data() {
var createFragmentSpecResolver = relay.environment.unstable_internal.createFragmentSpecResolver;
var resolver = createFragmentSpecResolver(relay, this.$options.name, fragments, this.$props, this._handleFragmentDataUpdate);
return {
// a.k.a this._relayContext in react-relay
context: Object.freeze({
relay: {
environment: relay.environment,
variables: relay.variables
}
}),
state: Object.freeze({
data: resolver.resolve(),
prevProps: this.$props,
relayEnvironment: relay.environment,
relayVariables: relay.variables,
relayProp: this._buildRelayProp(relay),
localVariables: null,
refetchSubscription: null,
resolver: resolver
})
};
},
methods: {
setState: function setState(state) {
this.state = Object.freeze(_extends({}, this.state, state));
},
_buildRelayProp: function _buildRelayProp(relay) {
return {
environment: relay.environment,
refetch: this._refetch
};
},
_handleFragmentDataUpdate: function _handleFragmentDataUpdate() {
this.setState({
data: this.state.resolver.resolve()
});
},
_getFragmentVariables: function _getFragmentVariables() {
var getVariablesFromObject = relay.environment.unstable_internal.getVariablesFromObject;
return getVariablesFromObject(relay.variables, fragments, this.$props);
},
_getQueryFetcher: function _getQueryFetcher() {
if (!this.state.queryFetcher) {
this.setState({ queryFetcher: new VueRelayQueryFetcher() });
}
return this.state.queryFetcher;
},
_refetch: function _refetch(refetchVariables, renderVariables, observerOrCallback, options) {
var _this = this;
var environment = relay.environment,
rootVariables = relay.variables;
var _environment$unstable = environment.unstable_internal,
createOperationSelector = _environment$unstable.createOperationSelector,
getRequest = _environment$unstable.getRequest;
var fetchVariables = typeof refetchVariables === 'function' ? refetchVariables(this._getFragmentVariables()) : refetchVariables;
fetchVariables = _extends({}, rootVariables, fetchVariables);
var fragmentVariables = renderVariables ? _extends({}, rootVariables, renderVariables) : fetchVariables;
this.setState({ localVariables: fetchVariables });
var cacheConfig = options ? { force: !!options.force } : void 0;
var observer = typeof observerOrCallback === 'function' ? {
// callback is not exectued on complete or unsubscribe
// for backward compatibility
next: observerOrCallback,
error: observerOrCallback
} : observerOrCallback || {};
var request = getRequest(taggedNode);
var operation = createOperationSelector(request, fetchVariables);
// Cancel any previously running refetch.
if (this.state.refetchSubscription) {
this.state.refetchSubscription.unsubscribe();
}
// Declare refetchSubscription before assigning it in .start(), since
// synchronous completion may call callbacks .subscribe() returns.
var refetchSubscription = void 0;
this._getQueryFetcher().execute({
environment: environment,
operation: operation,
cacheConfig: cacheConfig,
// TODO (T26430099): Cleanup old references
preservePreviousReferences: true
}).mergeMap(function (response) {
_this.context.relay.environment = relay.environment;
_this.context.relay.variables = fragmentVariables;
_this.state.resolver.setVariables(fragmentVariables);
return Observable.create(function (sink) {
_this.setState({ data: _this.state.resolver.resolve() });
sink.next();
sink.complete();
});
}).finally(function () {
// Finalizing a refetch should only clear this._refetchSubscription
// if the finizing subscription is the most recent call.
if (_this.state.refetchSubscription === refetchSubscription) {
_this.state.refetchSubscription.unsubscribe();
_this.setState({
refetchSubscription: null
});
}
}).subscribe(_extends({}, observer, {
start: function start(subscription) {
refetchSubscription = subscription;
_this.setState({
refetchSubscription: subscription
});
observer.start && observer.start(subscription);
}
}));
return {
dispose: function dispose() {
refetchSubscription && refetchSubscription.unsubscribe();
}
};
},
_release: function _release() {
this.state.resolver.dispose();
this.state.references.forEach(function (disposable) {
return disposable.dispose();
});
this.state.references.length = 0;
if (this.state.refetchSubscription) {
this.state.refetchSubscription.unsubscribe();
this.setState({
refetchSubscription: null
});
}
if (this.state.queryFetcher) {
this.state.queryFetcher.dispose();
}
}
},
watch: _extends({}, Object.keys(fragments).map(function (key) {
return defineProperty({}, key, function () {
var _relay$environment$un = relay.environment.unstable_internal,
createFragmentSpecResolver = _relay$environment$un.createFragmentSpecResolver,
getDataIDsFromObject = _relay$environment$un.getDataIDsFromObject;
var prevIDs = getDataIDsFromObject(fragments, this.state.prevProps);
var nextIDs = getDataIDsFromObject(fragments, this.$props);
// If the environment has changed or props point to new records then
// previously fetched data and any pending fetches no longer apply:
// - Existing references are on the old environment.
// - Existing references are based on old variables.
// - Pending fetches are for the previous records.
if (this.state.relayEnvironment !== relay.environment || this.state.relayVariables !== relay.variables || !areEqual$1(prevIDs, nextIDs)) {
this._release();
this.context.relay.environment = relay.environment;
this.context.relay.variables = relay.variables;
var resolver = createFragmentSpecResolver(relay, this.$options.name, fragments, this.$props, this._handleFragmentDataUpdate);
this.setState({
prevProps: this.$props,
relayEnvironment: relay.environment,
relayVariables: relay.variables,
relayProp: this._buildRelayProp(relay),
localVariables: null,
resolver: resolver
});
} else if (!this.state.localVariables) {
this.state.resolver.setProps(this.$props);
}
var data = this.state.resolver.resolve();
if (data !== this.state.data) {
this.setState({ data: data });
}
});
})),
beforeDestroy: function beforeDestroy() {
this._release();
}
};
};
var createRefetchContainer = function createRefetchContainer() {
invariant$2(arguments.length === 2 || arguments.length === 3, 'createRefetchContainer: Expected `arguments.length` to be 2 or 3, got `%s`.', arguments);
if (arguments.length === 2) {
[].unshift.call(arguments, null);
}
var _arguments = Array.prototype.slice.call(arguments),
component = _arguments[0],
fragmentSpec = _arguments[1],
taggedNode = _arguments[2];
return buildVueRelayContainer(component, fragmentSpec, function (fragments) {
return createContainerWithFragments.call(this, fragments, taggedNode);
});
};
var areEqual$2 = require('fbjs/lib/areEqual');
var invariant$3 = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var _require$1 = require('relay-runtime'),
ConnectionInterface = _require$1.ConnectionInterface,
Observable$1 = _require$1.Observable;
var FORWARD = 'forward';
var createGetConnectionFromProps = function createGetConnectionFromProps(metadata) {
var path = metadata.path;
invariant$3(path, 'RelayPaginationContainer: Unable to synthesize a ' + 'getConnectionFromProps function.');
return function (props) {
var data = props[metadata.fragmentName];
for (var i = 0; i < path.length; i++) {
if (!data || (typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object') {
return null;
}
data = data[path[i]];
}
return data;
};
};
var createGetFragmentVariables = function createGetFragmentVariables(metadata) {
var countVariable = metadata.count;
invariant$3(countVariable, 'RelayPaginationContainer: Unable to synthesize a ' + 'getFragmentVariables function.');
return function (prevVars, totalCount) {
return _extends({}, prevVars, defineProperty({}, countVariable, totalCount));
};
};
var findConnectionMetadata = function findConnectionMetadata(fragments) {
var foundConnectionMetadata = null;
var isRelayModern = false;
for (var fragmentName in fragments) {
var fragment = fragments[fragmentName];
var connectionMetadata = fragment.metadata && fragment.metadata.connection;
// HACK: metadata is always set to `undefined` in classic. In modern, even
// if empty, it is set to null (never undefined). We use that knowlege to
// check if we're dealing with classic or modern
if (fragment.metadata !== undefined) {
isRelayModern = true;
}
if (connectionMetadata) {
invariant$3(connectionMetadata.length === 1, 'RelayPaginationContainer: Only a single @connection is ' + 'supported, `%s` has %s.', fragmentName, connectionMetadata.length);
invariant$3(!foundConnectionMetadata, 'RelayPaginationContainer: Only a single fragment with ' + '@connection is supported.');
foundConnectionMetadata = _extends({}, connectionMetadata[0], {
fragmentName: fragmentName
});
}
}
invariant$3(!isRelayModern || foundConnectionMetadata !== null, 'RelayPaginationContainer: A @connection directive must be present.');
return foundConnectionMetadata || {};
};
var toObserver = function toObserver(observerOrCallback) {
return typeof observerOrCallback === 'function' ? {
error: observerOrCallback,
complete: observerOrCallback,
unsubscribe: function unsubscribe(subscription) {
typeof observerOrCallback === 'function' && observerOrCallback();
}
} : observerOrCallback || {};
};
var createContainerWithFragments$1 = function createContainerWithFragments(fragments, connectionConfig) {
var relay = this.relay;
var metadata = findConnectionMetadata(fragments);
var getConnectionFromProps = connectionConfig.getConnectionFromProps || createGetConnectionFromProps(metadata);
var direction = connectionConfig.direction || metadata.direction;
invariant$3(direction, 'RelayPaginationContainer: Unable to infer direction of the ' + 'connection, possibly because both first and last are provided.');
var getFragmentVariables = connectionConfig.getFragmentVariables || createGetFragmentVariables(metadata);
return {
name: 'relay-pagination-container',
data: function data() {
var createFragmentSpecResolver = relay.environment.unstable_internal.createFragmentSpecResolver;
var resolver = createFragmentSpecResolver(relay, this.$options.name, fragments, this.$props, this._handleFragmentDataUpdate);
return {
// a.k.a this._relayContext in react-relay
context: Object.freeze({
relay: {
environment: relay.environment,
variables: relay.variables
}
}),
state: Object.freeze({
data: resolver.resolve(),
prevProps: this.$props,
relayEnvironment: relay.environment,
relayVariables: relay.variables,
relayProp: this._buildRelayProp(relay),
isARequestInFlight: false,
localVariables: null,
refetchSubscription: null,
resolver: resolver
})
};
},
methods: {
setState: function setState(state) {
this.state = Object.freeze(_extends({}, this.state, state));
},
_buildRelayProp: function _buildRelayProp(relay) {
return {
hasMore: this._hasMore,
isLoading: this._isLoading,
loadMore: this._loadMore,
refetchConnection: this._refetchConnection,
environment: relay.environment
};
},
_handleFragmentDataUpdate: function _handleFragmentDataUpdate() {
this.setState({
data: this.state.resolver.resolve()
});
},
_getConnectionData: function _getConnectionData() {
// Extract connection data and verify there are more edges to fetch
var props = _extends({}, this.$props, this.state.data);
var connectionData = getConnectionFromProps(props);
if (connectionData == null) {
return null;
}
var _ConnectionInterface$ = ConnectionInterface.get(),
EDGES = _ConnectionInterface$.EDGES,
PAGE_INFO = _ConnectionInterface$.PAGE_INFO,
HAS_NEXT_PAGE = _ConnectionInterface$.HAS_NEXT_PAGE,
HAS_PREV_PAGE = _ConnectionInterface$.HAS_PREV_PAGE,
END_CURSOR = _ConnectionInterface$.END_CURSOR,
START_CURSOR = _ConnectionInterface$.START_CURSOR;
invariant$3((typeof connectionData === 'undefined' ? 'undefined' : _typeof(connectionData)) === 'object', 'RelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return `null` or a plain object with %s and %s properties, got `%s`.', this.$options.name, EDGES, PAGE_INFO, connectionData);
var edges = connectionData[EDGES];
var pageInfo = connectionData[PAGE_INFO];
if (edges == null || pageInfo == null) {
return null;
}
invariant$3(Array.isArray(edges), 'RelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return an object with %s: Array, got `%s`.', this.$options.name, EDGES, edges);
invariant$3((typeof pageInfo === 'undefined' ? 'undefined' : _typeof(pageInfo)) === 'object', 'RelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' + 'to return an object with %s: Object, got `%s`.', this.$options.name, PAGE_INFO, pageInfo);
var hasMore = direction === FORWARD ? pageInfo[HAS_NEXT_PAGE] : pageInfo[HAS_PREV_PAGE];
var cursor = direction === FORWARD ? pageInfo[END_CURSOR] : pageInfo[START_CURSOR];
if (typeof hasMore !== 'boolean' || edges.length !== 0 && typeof cursor === 'undefined') {
warning(false, 'RelayPaginationContainer: Cannot paginate without %s fields in `%s`. ' + 'Be sure to fetch %s (got `%s`) and %s (got `%s`).', PAGE_INFO, this.$options.name, direction === FORWARD ? HAS_NEXT_PAGE : HAS_PREV_PAGE, hasMore, direction === FORWARD ? END_CURSOR : START_CURSOR, cursor);
return null;
}
return {
cursor: cursor,
edgeCount: edges.length,
hasMore: hasMore
};
},
_hasMore: function _hasMore() {
var connectionData = this._getConnectionData();
return !!(connectionData && connectionData.hasMore && connectionData.cursor);
},
_isLoading: function _isLoading() {
return !!this.state.refetchSubscription;
},
_refetchConnection: function _refetchConnection(totalCount, observerOrCallback, refetchVariables) {
var paginatingVariables = {
count: totalCount,
cursor: null,
totalCount: totalCount
};
var fetch = this._fetchPage(paginatingVariables, toObserver(observerOrCallback), { force: true }, refetchVariables);
return { dispose: fetch.unsubscribe };
},
_loadMore: function _loadMore(pageSize, observerOrCallback, options) {
var observer = toObserver(observerOrCallback);
var connectionData = this._getConnectionData();
if (!connectionData) {
Observable$1.create(function (sink) {
return sink.complete();
}).subscribe(observer);
return null;
}
var totalCount = connectionData.edgeCount + pageSize;
if (options && options.force) {
return this._refetchConnection(totalCount, observerOrCallback);
}
var _ConnectionInterface$2 = ConnectionInterface.get(),
END_CURSOR = _ConnectionInterface$2.END_CURSOR,
START_CURSOR = _ConnectionInterface$2.START_CURSOR;
var cursor = connectionData.cursor;
warning(cursor, 'RelayPaginationContainer: Cannot `loadMore` without valid `%s` (got `%s`)', direction === FORWARD ? END_CURSOR : START_CURSOR, cursor);
var paginatingVariables = {
count: pageSize,
cursor: cursor,
totalCount: totalCount
};
var fetch = this._fetchPage(paginatingVariables, observer, options);
return { dispose: fetch.unsubscribe };
},
_getQueryFetcher: function _getQueryFetcher() {
if (!this.state.queryFetcher) {
this.setState({ queryFetcher: new VueRelayQueryFetcher() });
}
return this.state.queryFetcher;
},
_fetchPage: function _fetchPage(paginatingVariables, observer, options, refetchVariables) {
var _this = this;
var environment = relay.environment;
var _environment$unstable = environment.unstable_internal,
createOperationSelector = _environment$unstable.createOperationSelector,
getRequest = _environment$unstable.getRequest,
getVariablesFromObject = _environment$unstable.getVariablesFromObject;
var props = _extends({}, this.$props, this.state.data);
var fragmentVariables = getVariablesFromObject(this.context.relay.variables, fragments, this.$props);
fragmentVariables = _extends({}, fragmentVariables, refetchVariables);
var fetchVariables = connectionConfig.getVariables(props, {
count: paginatingVariables.count,
cursor: paginatingVariables.cursor
},
// Pass the variables used to fetch the fragments initially
fragmentVariables);
invariant$3((typeof fetchVariables === 'undefined' ? 'undefined' : _typeof(fetchVariables)) === 'object' && fetchVariables !== null, 'RelayPaginationContainer: Expected `getVariables()` to ' + 'return an object, got `%s` in `%s`.', fetchVariables, this.$options.name);