-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
RelayContainer.js
1197 lines (1124 loc) · 38.4 KB
/
RelayContainer.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const ErrorUtils = require('ErrorUtils');
const React = require('React');
const ReactRelayContext = require('../../modern/ReactRelayContext');
const RelayContainerComparators = require('./RelayContainerComparators');
const RelayContainerProxy = require('./RelayContainerProxy');
const RelayFragmentPointer = require('../query/RelayFragmentPointer');
const RelayFragmentReference = require('../query/RelayFragmentReference');
const RelayMetaRoute = require('../route/RelayMetaRoute');
const RelayMutationTransaction = require('../mutation/RelayMutationTransaction');
const RelayQuery = require('../query/RelayQuery');
const RelayRecord = require('../store/RelayRecord');
const RelayRecordStatusMap = require('../store/RelayRecordStatusMap');
const areEqual = require('areEqual');
const buildRQL = require('../query/buildRQL');
const filterObject = require('filterObject');
const forEachObject = require('forEachObject');
const invariant = require('invariant');
const isClassicRelayContext = require('../store/isClassicRelayContext');
const makeLegacyStringishComponentRef = require('../util/makeLegacyStringishComponentRef');
const relayUnstableBatchedUpdates = require('../tools/relayUnstableBatchedUpdates');
const shallowEqual = require('shallowEqual');
const warning = require('warning');
const {getComponentName} = require('../../modern/ReactRelayContainerUtils');
const {getReactComponent} = require('./RelayClassicContainerUtils');
const {RelayProfiler} = require('relay-runtime');
import type {RelayQueryConfigInterface} from '../query-config/RelayQueryConfig';
import type {ConcreteFragment} from '../query/ConcreteQuery';
import type {RelayQLFragmentBuilder} from '../query/buildRQL';
import type {
FragmentResolver,
ClassicRelayContext,
} from '../store/RelayEnvironment';
import type {RelayQuerySet} from '../tools/RelayInternalTypes';
import type {
Abortable,
ComponentReadyStateChangeCallback,
RelayProp,
} from '../tools/RelayTypes';
import type {DataID, Variables} from 'relay-runtime';
type FragmentPointer = {
fragment: RelayQuery.Fragment,
dataIDs: DataID | Array<DataID>,
};
type ReactRelayContextType = ClassicRelayContext & {
route: RelayQueryConfigInterface,
useFakeData: boolean,
};
export type RelayContainerSpec = {
fragments: {
[propName: string]: RelayQLFragmentBuilder,
},
initialVariables?: Variables,
prepareVariables?: (
prevVariables: Variables,
route: RelayMetaRoute,
) => Variables,
shouldComponentUpdate?: () => boolean,
};
export type RelayLazyContainer = Function;
/**
* @public
*
* RelayContainer is a higher order component that provides the ability to:
*
* - Encode data dependencies using query fragments that are parameterized by
* routes and variables.
* - Manipulate variables via methods on `this.props.relay`.
* - Automatically subscribe to data changes.
* - Avoid unnecessary updates if data is unchanged.
* - Propagate the `route` via context (available on `this.props.relay`).
*
*/
function createContainerComponent(
Component: React.ComponentType<any>,
spec: RelayContainerSpec,
): $FlowFixMe {
const ComponentClass = getReactComponent(Component);
const componentName = getComponentName(Component);
const containerName = getContainerName(Component);
const fragments = spec.fragments;
const fragmentNames = Object.keys(fragments);
const initialVariables = spec.initialVariables || {};
const prepareVariables = spec.prepareVariables;
const specShouldComponentUpdate = spec.shouldComponentUpdate;
class RelayContainer extends React.Component<
$FlowFixMeProps,
{
queryData: {[propName: string]: mixed},
rawVariables: Variables,
relayProp: RelayProp,
},
> {
mounted: boolean;
_didShowFakeDataWarning: boolean;
_fragmentPointers: {[key: string]: ?FragmentPointer};
_hasStaleQueryData: boolean;
_fragmentResolvers: {[key: string]: ?FragmentResolver};
pending: ?{
rawVariables: Variables,
request: Abortable,
};
constructor(props) {
super(props);
const {route} = props.__relayContext;
invariant(
isClassicRelayContext({
variables: props.__relayContext.variables,
environment: props.__relayContext.environment,
}),
'RelayContainer: `%s` was rendered with invalid Relay context `%s`. ' +
'Make sure the `relay` property on the React context conforms to the ' +
'`RelayEnvironment` interface.',
containerName,
props.__relayContext,
);
invariant(
route && typeof route.name === 'string',
'RelayContainer: `%s` was rendered without a valid route. Make sure ' +
'the route is valid, and make sure that it is correctly set on the ' +
"parent component's context (e.g. using <RelayRootContainer>).",
containerName,
);
this._didShowFakeDataWarning = false;
this._fragmentPointers = {};
this._hasStaleQueryData = false;
this._fragmentResolvers = {};
this.mounted = true;
this.pending = null;
this.state = {
queryData: {},
rawVariables: {},
relayProp: {
applyUpdate: this.props.__relayContext.environment.applyUpdate,
commitUpdate: this.props.__relayContext.environment.commitUpdate,
environment: this.props.__relayContext.environment,
forceFetch: this.forceFetch.bind(this),
getPendingTransactions: this.getPendingTransactions.bind(this),
hasFragmentData: this.hasFragmentData.bind(this),
hasOptimisticUpdate: this.hasOptimisticUpdate.bind(this),
hasPartialData: this.hasPartialData.bind(this),
pendingVariables: null,
route,
setVariables: this.setVariables.bind(this),
variables: {},
},
};
}
/**
* Requests an update to variables. This primes the cache for the new
* variables and notifies the caller of changes via the callback. As data
* becomes ready, the component will be updated.
*/
setVariables(
partialVariables?: ?Variables,
callback?: ?ComponentReadyStateChangeCallback,
): void {
this._runVariables(partialVariables, callback, false);
}
/**
* Requests an update to variables. Unlike `setVariables`, this forces data
* to be fetched and written for the supplied variables. Any data that
* previously satisfied the queries will be overwritten.
*/
forceFetch(
partialVariables?: ?Variables,
callback?: ?ComponentReadyStateChangeCallback,
): void {
this._runVariables(partialVariables, callback, true);
}
/**
* Creates a query for each of the component's fragments using the given
* variables, and fragment pointers that can be used to resolve the results
* of those queries. The fragment pointers are of the same shape as the
* `_fragmentPointers` property.
*/
_createQuerySetAndFragmentPointers(
variables: Variables,
): {
fragmentPointers: {[key: string]: ?FragmentPointer},
querySet: RelayQuerySet,
} {
const fragmentPointers = {};
const querySet = {};
const storeData = this.props.__relayContext.environment.getStoreData();
fragmentNames.forEach(fragmentName => {
const fragment = getFragment(
fragmentName,
this.props.__relayContext.route,
variables,
);
const queryData = this.state.queryData[fragmentName];
if (!fragment || queryData == null) {
return;
}
let fragmentPointer;
if (fragment.isPlural()) {
invariant(
Array.isArray(queryData),
'RelayContainer: Invalid queryData for `%s`, expected an array ' +
'of records because the corresponding fragment is plural.',
fragmentName,
);
const dataIDs = [];
queryData.forEach((data, ii) => {
/* $FlowFixMe(>=0.36.0) Flow error detected
* during the deploy of Flow v0.36.0. To see the error, remove this
* comment and run Flow */
const dataID = RelayRecord.getDataIDForObject(data);
if (dataID) {
querySet[
fragmentName + ii
] = storeData.buildFragmentQueryForDataID(fragment, dataID);
dataIDs.push(dataID);
}
});
if (dataIDs.length) {
fragmentPointer = {fragment, dataIDs};
}
} else {
/* $FlowFixMe(>=0.19.0) - queryData is mixed but getID expects Object
*/
const dataID = RelayRecord.getDataIDForObject(queryData);
if (dataID) {
fragmentPointer = {
fragment,
dataIDs: dataID,
};
querySet[fragmentName] = storeData.buildFragmentQueryForDataID(
fragment,
dataID,
);
}
}
fragmentPointers[fragmentName] = fragmentPointer;
});
return {fragmentPointers, querySet};
}
_runVariables(
partialVariables: ?Variables,
callback: ?ComponentReadyStateChangeCallback,
forceFetch: boolean,
): void {
validateVariables(initialVariables, partialVariables);
const lastVariables = this.state.rawVariables;
const prevVariables = this.pending
? this.pending.rawVariables
: lastVariables;
const rawVariables = mergeVariables(prevVariables, partialVariables);
let nextVariables = rawVariables;
if (prepareVariables) {
const metaRoute = RelayMetaRoute.get(
this.props.__relayContext.route.name,
);
nextVariables = prepareVariables(rawVariables, metaRoute);
validateVariables(initialVariables, nextVariables);
}
this.pending && this.pending.request.abort();
const completeProfiler = RelayProfiler.profile(
'RelayContainer.setVariables',
{
containerName,
nextVariables,
},
);
// Because the pending fetch is always canceled, we need to build a new
// set of queries that includes the updated variables and initiate a new
// fetch.
const {
querySet,
fragmentPointers,
} = this._createQuerySetAndFragmentPointers(nextVariables);
const onReadyStateChange = ErrorUtils.guard(readyState => {
const {aborted, done, error, ready} = readyState;
const isComplete = aborted || done || error;
if (isComplete && this.pending === current) {
this.pending = null;
}
let partialState;
if (ready) {
// Only update query data if variables changed. Otherwise, `querySet`
// and `fragmentPointers` will be empty, and `nextVariables` will be
// equal to `lastVariables`.
this._fragmentPointers = fragmentPointers;
this._updateFragmentResolvers(this.props.__relayContext.environment);
const queryData = this._getQueryData(this.props);
partialState = {
queryData,
rawVariables,
relayProp: {
...this.state.relayProp,
pendingVariables: null,
variables: nextVariables,
},
};
} else {
partialState = {
relayProp: {
...this.state.relayProp,
pendingVariables: isComplete ? null : nextVariables,
},
};
}
const mounted = this.mounted;
if (mounted) {
const updateProfiler = RelayProfiler.profile('RelayContainer.update');
relayUnstableBatchedUpdates(() => {
this.setState(partialState, () => {
updateProfiler.stop();
if (isComplete) {
completeProfiler.stop();
}
});
if (callback) {
callback.call(
// eslint-disable-next-line react/no-string-refs
this.refs.component || null,
{...readyState, mounted},
);
}
});
} else {
if (callback) {
callback({...readyState, mounted});
}
if (isComplete) {
completeProfiler.stop();
}
}
}, 'RelayContainer.onReadyStateChange');
const current = {
rawVariables,
request: forceFetch
? this.props.__relayContext.environment.forceFetch(
querySet,
onReadyStateChange,
)
: this.props.__relayContext.environment.primeCache(
querySet,
onReadyStateChange,
),
};
this.pending = current;
}
/**
* Determine if the supplied record reflects an optimistic update.
*/
hasOptimisticUpdate(record: Object): boolean {
const dataID = RelayRecord.getDataIDForObject(record);
invariant(
dataID != null,
'RelayContainer.hasOptimisticUpdate(): Expected a record in `%s`.',
componentName,
);
return this.props.__relayContext.environment
.getStoreData()
.hasOptimisticUpdate(dataID);
}
/**
* Returns the pending mutation transactions affecting the given record.
*/
getPendingTransactions(record: Object): ?Array<RelayMutationTransaction> {
const dataID = RelayRecord.getDataIDForObject(record);
invariant(
dataID != null,
'RelayContainer.getPendingTransactions(): Expected a record in `%s`.',
componentName,
);
const storeData = this.props.__relayContext.environment.getStoreData();
const mutationIDs = storeData.getClientMutationIDs(dataID);
if (!mutationIDs) {
return null;
}
const mutationQueue = storeData.getMutationQueue();
return mutationIDs.map(id => mutationQueue.getTransaction(id));
}
/**
* Checks if data for a deferred fragment is ready. This method should
* *always* be called before rendering a child component whose fragment was
* deferred (unless that child can handle null or missing data).
*/
hasFragmentData(
fragmentReference: RelayFragmentReference,
record: Object,
): boolean {
// convert builder -> fragment in order to get the fragment's name
const dataID = RelayRecord.getDataIDForObject(record);
invariant(
dataID != null,
'RelayContainer.hasFragmentData(): Second argument is not a valid ' +
'record. For `<%s X={this.props.X} />`, use ' +
"`this.props.hasFragmentData(%s.getFragment('X'), this.props.X)`.",
componentName,
componentName,
);
const fragment = getDeferredFragment(
fragmentReference,
this.props.__relayContext,
this.state.relayProp.variables,
);
invariant(
fragment instanceof RelayQuery.Fragment,
'RelayContainer.hasFragmentData(): First argument is not a valid ' +
'fragment. Ensure that there are no failing `if` or `unless` ' +
'conditions.',
);
const storeData = this.props.__relayContext.environment.getStoreData();
return storeData
.getCachedStore()
.hasFragmentData(dataID, fragment.getCompositeHash());
}
/**
* Determine if the supplied record might be missing data.
*/
hasPartialData(record: Object): boolean {
return RelayRecordStatusMap.isPartialStatus(
record[RelayRecord.MetadataKey.STATUS],
);
}
UNSAFE_componentWillMount(): void {
if (this.props.__relayContext.route.useMockData) {
return;
}
this.setState(
this._initialize(
this.props,
this.props.__relayContext,
initialVariables,
null,
),
);
}
UNSAFE_componentWillReceiveProps(nextProps: Object): void {
invariant(
nextProps.__relayContext,
'RelayContainer: Expected a context to be set.',
);
if (nextProps.__relayContext.route.useMockData) {
return;
}
this.setState(state => {
if (
this.props.__relayContext.environment !==
nextProps.__relayContext.environment ||
this.props.__relayContext.variables !==
nextProps.__relayContext.variables
) {
this._cleanup();
}
return this._initialize(
nextProps,
nextProps.__relayContext,
resetPropOverridesForVariables(spec, nextProps, state.rawVariables),
state.rawVariables,
);
});
}
componentWillUnmount(): void {
this._cleanup();
this.mounted = false;
}
_initialize(
props: Object,
context: ReactRelayContextType,
propVariables: Variables,
prevVariables: ?Variables,
): {
queryData: {[propName: string]: mixed},
rawVariables: Variables,
relayProp: RelayProp,
} {
const rawVariables = getVariablesWithPropOverrides(
spec,
props,
propVariables,
);
let nextVariables = rawVariables;
if (prepareVariables) {
// TODO: Allow routes without names, #7856965.
const metaRoute = RelayMetaRoute.get(context.route.name);
nextVariables = prepareVariables(rawVariables, metaRoute);
validateVariables(initialVariables, nextVariables);
}
this._updateFragmentPointers(
props,
context,
nextVariables,
prevVariables,
);
this._updateFragmentResolvers(context.environment);
return {
queryData: this._getQueryData(props),
rawVariables,
relayProp:
this.state.relayProp.route === context.route &&
shallowEqual(this.state.relayProp.variables, nextVariables)
? this.state.relayProp
: {
...this.state.relayProp,
route: context.route,
variables: nextVariables,
},
};
}
_cleanup(): void {
// A guarded error in mounting might prevent initialization of resolvers.
if (this._fragmentResolvers) {
forEachObject(this._fragmentResolvers, fragmentResolver => {
fragmentResolver && fragmentResolver.dispose();
});
}
this._fragmentPointers = {};
this._fragmentResolvers = {};
const pending = this.pending;
if (pending) {
pending.request.abort();
this.pending = null;
}
}
_updateFragmentResolvers(environment): void {
const fragmentPointers = this._fragmentPointers;
const fragmentResolvers = this._fragmentResolvers;
fragmentNames.forEach(fragmentName => {
const fragmentPointer = fragmentPointers[fragmentName];
let fragmentResolver = fragmentResolvers[fragmentName];
if (!fragmentPointer) {
if (fragmentResolver) {
fragmentResolver.dispose();
fragmentResolvers[fragmentName] = null;
}
} else if (!fragmentResolver) {
fragmentResolver = environment.getFragmentResolver(
fragmentPointer.fragment,
this._handleFragmentDataUpdate.bind(this),
);
fragmentResolvers[fragmentName] = fragmentResolver;
}
});
}
_handleFragmentDataUpdate(): void {
if (!this.mounted) {
return;
}
const queryData = this._getQueryData(this.props);
const updateProfiler = RelayProfiler.profile(
'RelayContainer.handleFragmentDataUpdate',
);
this.setState({queryData}, updateProfiler.stop);
}
_updateFragmentPointers(
props: Object,
context: ReactRelayContextType,
variables: Variables,
prevVariables: ?Variables,
): void {
const fragmentPointers = this._fragmentPointers;
fragmentNames.forEach(fragmentName => {
const propValue = props[fragmentName];
warning(
propValue !== undefined,
'RelayContainer: Expected prop `%s` to be supplied to `%s`, but ' +
'got `undefined`. Pass an explicit `null` if this is intentional.',
fragmentName,
componentName,
);
if (propValue == null) {
fragmentPointers[fragmentName] = null;
return;
}
// handle invalid prop values using a warning at first.
if (typeof propValue !== 'object') {
warning(
false,
'RelayContainer: Expected prop `%s` supplied to `%s` to be an ' +
'object, got `%s`.',
fragmentName,
componentName,
propValue,
);
fragmentPointers[fragmentName] = null;
return;
}
const fragment = getFragment(fragmentName, context.route, variables);
let dataIDOrIDs;
if (fragment.isPlural()) {
// Plural fragments require the prop value to be an array of fragment
// pointers, which are merged into a single fragment pointer to pass
// to the query resolver `resolve`.
invariant(
Array.isArray(propValue),
'RelayContainer: Invalid prop `%s` supplied to `%s`, expected an ' +
'array of records because the corresponding fragment has ' +
'`@relay(plural: true)`.',
fragmentName,
componentName,
);
if (!propValue.length) {
// Nothing to observe: pass the empty array through
fragmentPointers[fragmentName] = null;
return;
}
let dataIDs = null;
propValue.forEach((item, ii) => {
if (typeof item === 'object' && item != null) {
if (RelayFragmentPointer.hasConcreteFragment(item, fragment)) {
const dataID = RelayRecord.getDataIDForObject(item);
if (dataID) {
dataIDs = dataIDs || [];
dataIDs.push(dataID);
}
}
if (__DEV__) {
if (
!context.route.useMockData &&
!context.useFakeData &&
!this._didShowFakeDataWarning
) {
const isValid = validateFragmentProp(
componentName,
fragmentName,
fragment,
item,
prevVariables,
);
this._didShowFakeDataWarning = !isValid;
}
}
}
});
if (dataIDs) {
invariant(
dataIDs.length === propValue.length,
'RelayContainer: Invalid prop `%s` supplied to `%s`. Some ' +
'array items contain data fetched by Relay and some items ' +
'contain null/mock data.',
fragmentName,
componentName,
);
}
dataIDOrIDs = dataIDs;
} else {
invariant(
!Array.isArray(propValue),
'RelayContainer: Invalid prop `%s` supplied to `%s`, expected a ' +
'single record because the corresponding fragment is not plural ' +
'(i.e. does not have `@relay(plural: true)`).',
fragmentName,
componentName,
);
if (RelayFragmentPointer.hasConcreteFragment(propValue, fragment)) {
dataIDOrIDs = RelayRecord.getDataIDForObject(propValue);
}
if (__DEV__) {
if (
!context.route.useMockData &&
!context.useFakeData &&
!this._didShowFakeDataWarning
) {
const isValid = validateFragmentProp(
componentName,
fragmentName,
fragment,
propValue,
prevVariables,
);
this._didShowFakeDataWarning = !isValid;
}
}
}
fragmentPointers[fragmentName] = dataIDOrIDs
? {fragment, dataIDs: dataIDOrIDs}
: null;
});
if (__DEV__) {
// If a fragment pointer is null, warn if it was found on another prop.
fragmentNames.forEach(fragmentName => {
if (fragmentPointers[fragmentName]) {
return;
}
const fragment = getFragment(fragmentName, context.route, variables);
Object.keys(props).forEach(propName => {
warning(
fragmentPointers[propName] ||
!RelayRecord.isRecord(props[propName]) ||
typeof props[propName] !== 'object' ||
props[propName] == null ||
!RelayFragmentPointer.hasFragment(props[propName], fragment),
'RelayContainer: Expected record data for prop `%s` on `%s`, ' +
'but it was instead on prop `%s`. Did you misspell a prop or ' +
'pass record data into the wrong prop?',
fragmentName,
componentName,
propName,
);
});
});
}
}
_getQueryData(props: Object): Object {
const queryData = {};
const fragmentPointers = this._fragmentPointers;
forEachObject(this._fragmentResolvers, (fragmentResolver, propName) => {
const propValue = props[propName];
const fragmentPointer = fragmentPointers[propName];
if (!propValue || !fragmentPointer) {
// Clear any subscriptions since there is no data.
fragmentResolver && fragmentResolver.dispose();
// Allow mock data to pass through without modification.
queryData[propName] = propValue;
} else {
invariant(fragmentResolver, 'fragmentResolver should not be null');
queryData[propName] = fragmentResolver.resolve(
fragmentPointer.fragment,
fragmentPointer.dataIDs,
);
}
if (
this.state.queryData.hasOwnProperty(propName) &&
queryData[propName] !== this.state.queryData[propName]
) {
this._hasStaleQueryData = true;
}
});
return queryData;
}
shouldComponentUpdate(nextProps: Object, nextState: any): boolean {
if (specShouldComponentUpdate) {
return specShouldComponentUpdate();
}
// Flag indicating that query data changed since previous render.
if (this._hasStaleQueryData) {
this._hasStaleQueryData = false;
return true;
}
if (
this.props.__relayContext.environment !==
nextProps.__relayContext.environment ||
this.props.__relayContext.variables !==
nextProps.__relayContext.variables ||
this.props.__relayContext.route !== nextProps.__relayContext.route
) {
return true;
}
if (this.props.__relayContext.route.useMockData) {
return true;
}
const {__relayContext, ...props} = this.props;
const {__relayContext: _, ...actualNextProps} = nextProps;
const fragmentPointers = this._fragmentPointers;
return (
!RelayContainerComparators.areNonQueryPropsEqual(
fragments,
props,
actualNextProps,
) ||
(fragmentPointers &&
!RelayContainerComparators.areQueryResultsEqual(
fragmentPointers,
this.state.queryData,
nextState.queryData,
)) ||
!RelayContainerComparators.areQueryVariablesEqual(
this.state.relayProp.variables,
nextState.relayProp.variables,
)
);
}
render(): React.Node {
if (ComponentClass) {
return (
<ComponentClass
{...this.props}
{...this.state.queryData}
ref={this._legacyStringishRef}
relay={this.state.relayProp}
/>
);
} else {
// Stateless functional.
const Fn = (Component: any);
return React.createElement(Fn, {
...this.props,
...this.state.queryData,
relay: this.state.relayProp,
});
}
}
// @TODO (T28161354) Remove this once string ref usage is gone.
_legacyStringishRef = makeLegacyStringishComponentRef(this, componentName);
}
function getFragment(
fragmentName: string,
route: RelayQueryConfigInterface,
variables: Variables,
): RelayQuery.Fragment {
const fragmentBuilder = fragments[fragmentName];
invariant(
fragmentBuilder,
'RelayContainer: Expected `%s` to have a query fragment named `%s`.',
containerName,
fragmentName,
);
const fragment = buildContainerFragment(
containerName,
fragmentName,
fragmentBuilder,
initialVariables,
);
// TODO: Allow routes without names, #7856965.
const metaRoute = RelayMetaRoute.get(route.name);
return RelayQuery.Fragment.create(fragment, metaRoute, variables);
}
initializeProfiler(RelayContainer);
RelayContainer.displayName = containerName;
RelayContainerProxy.proxyMethods(RelayContainer, Component);
return RelayContainer;
}
/**
* TODO: Stop allowing props to override variables, #7856288.
*/
function getVariablesWithPropOverrides(
spec: RelayContainerSpec,
props: Object,
variables: Variables,
): Variables {
const initialVariables = spec.initialVariables;
if (initialVariables) {
let mergedVariables;
for (const key in initialVariables) {
if (key in props) {
mergedVariables = mergedVariables || {...variables};
mergedVariables[key] = props[key];
}
}
variables = mergedVariables || variables;
}
return variables;
}
/**
* Compare props and variables and reset the internal query variables if outside
* query variables change the component.
*
* TODO: Stop allowing props to override variables, #7856288.
*/
function resetPropOverridesForVariables(
spec: RelayContainerSpec,
props: Object,
variables: Variables,
): Variables {
const initialVariables = spec.initialVariables;
for (const key in initialVariables) {
if (key in props && !areEqual(props[key], variables[key])) {
return initialVariables;
}
}
return variables;
}
function initializeProfiler(RelayContainer: $FlowFixMe): void {
RelayProfiler.instrumentMethods(RelayContainer.prototype, {
UNSAFE_componentWillMount:
'RelayContainer.prototype.UNSAFE_componentWillMount',
UNSAFE_componentWillReceiveProps:
'RelayContainer.prototype.UNSAFE_componentWillReceiveProps',
shouldComponentUpdate: 'RelayContainer.prototype.shouldComponentUpdate',
});
}
/**
* Merges a partial update into a set of variables. If no variables changed, the
* same object is returned. Otherwise, a new object is returned.
*/
function mergeVariables(
currentVariables: Variables,
partialVariables: ?Variables,
): Variables {
if (partialVariables) {
for (const key in partialVariables) {
if (currentVariables[key] !== partialVariables[key]) {
return {...currentVariables, ...partialVariables};
}
}
}
return currentVariables;
}
/**
* Wrapper around `buildRQL.Fragment` with contextual error messages.
*/
function buildContainerFragment(
containerName: string,
fragmentName: string,
fragmentBuilder: RelayQLFragmentBuilder,
variables: Variables,
): ConcreteFragment {
const fragment = buildRQL.Fragment(fragmentBuilder, variables);
invariant(
fragment,
'Relay.QL defined on container `%s` named `%s` is not a valid fragment. ' +
'A typical fragment is defined using: Relay.QL`fragment on Type {...}`',
containerName,
fragmentName,
);
return fragment;
}
function getDeferredFragment(
fragmentReference: RelayFragmentReference,
context: Object,
variables: Variables,
): RelayQuery.Fragment {
const route = RelayMetaRoute.get(context.route.name);
const concreteFragment = fragmentReference.getFragment(variables);
const concreteVariables = fragmentReference.getVariables(route, variables);
return RelayQuery.Fragment.create(
concreteFragment,
route,
concreteVariables,
{
isDeferred: true,
isContainerFragment: fragmentReference.isContainerFragment(),
isTypeConditional: false,
},
);
}
function validateVariables(
initialVariables: Variables,
partialVariables: ?Variables,
): void {
if (partialVariables) {
for (const key in partialVariables) {
warning(
initialVariables.hasOwnProperty(key),
'RelayContainer: Expected query variable `%s` to be initialized in ' +
'`initialVariables`.',
key,
);