relay-forms-nodeps 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.babelrc.js +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +124 -0
  4. package/lib/RelayFormsTypes.d.ts +37 -0
  5. package/lib/RelayFormsTypes.js +5 -0
  6. package/lib/Utils.d.ts +11 -0
  7. package/lib/Utils.js +87 -0
  8. package/lib/es/RelayFormsTypes.d.ts +37 -0
  9. package/lib/es/RelayFormsTypes.js +0 -0
  10. package/lib/es/Utils.d.ts +11 -0
  11. package/lib/es/Utils.js +81 -0
  12. package/lib/es/index.d.ts +9 -0
  13. package/lib/es/index.js +7 -0
  14. package/lib/es/relay/RelayModernRecord.d.ts +107 -0
  15. package/lib/es/relay/RelayModernRecord.js +183 -0
  16. package/lib/es/relay/RelayModernSelector.d.ts +11 -0
  17. package/lib/es/relay/RelayModernSelector.js +29 -0
  18. package/lib/es/relay/RelayModernStore.d.ts +51 -0
  19. package/lib/es/relay/RelayModernStore.js +355 -0
  20. package/lib/es/relay/RelayReader.d.ts +14 -0
  21. package/lib/es/relay/RelayReader.js +86 -0
  22. package/lib/es/relay/RelayRecordProxy.d.ts +28 -0
  23. package/lib/es/relay/RelayRecordProxy.js +57 -0
  24. package/lib/es/relay/RelayRecordSource.d.ts +28 -0
  25. package/lib/es/relay/RelayRecordSource.js +70 -0
  26. package/lib/es/relay/RelayRecordSourceMutator.d.ts +36 -0
  27. package/lib/es/relay/RelayRecordSourceMutator.js +75 -0
  28. package/lib/es/relay/RelayRecordSourceProxy.d.ts +25 -0
  29. package/lib/es/relay/RelayRecordSourceProxy.js +52 -0
  30. package/lib/es/relay/RelayReferenceMarker.d.ts +10 -0
  31. package/lib/es/relay/RelayReferenceMarker.js +54 -0
  32. package/lib/es/relay/RelayStoreProvider.d.ts +7 -0
  33. package/lib/es/relay/RelayStoreProvider.js +16 -0
  34. package/lib/es/relay/RelayStoreUtils.d.ts +51 -0
  35. package/lib/es/relay/RelayStoreUtils.js +199 -0
  36. package/lib/es/relay/RelayTypes.d.ts +92 -0
  37. package/lib/es/relay/RelayTypes.js +0 -0
  38. package/lib/es/relay/queries.d.ts +86 -0
  39. package/lib/es/relay/queries.js +68 -0
  40. package/lib/es/useForceUpdate.d.ts +1 -0
  41. package/lib/es/useForceUpdate.js +8 -0
  42. package/lib/es/useFormSetValue.d.ts +2 -0
  43. package/lib/es/useFormSetValue.js +84 -0
  44. package/lib/es/useFormState.d.ts +2 -0
  45. package/lib/es/useFormState.js +49 -0
  46. package/lib/es/useFormSubmit.d.ts +2 -0
  47. package/lib/es/useFormSubmit.js +105 -0
  48. package/lib/es/useFormValue.d.ts +2 -0
  49. package/lib/es/useFormValue.js +19 -0
  50. package/lib/index.d.ts +9 -0
  51. package/lib/index.js +20 -0
  52. package/lib/relay/RelayModernRecord.d.ts +107 -0
  53. package/lib/relay/RelayModernRecord.js +188 -0
  54. package/lib/relay/RelayModernSelector.d.ts +11 -0
  55. package/lib/relay/RelayModernSelector.js +36 -0
  56. package/lib/relay/RelayModernStore.d.ts +51 -0
  57. package/lib/relay/RelayModernStore.js +359 -0
  58. package/lib/relay/RelayReader.d.ts +14 -0
  59. package/lib/relay/RelayReader.js +92 -0
  60. package/lib/relay/RelayRecordProxy.d.ts +28 -0
  61. package/lib/relay/RelayRecordProxy.js +60 -0
  62. package/lib/relay/RelayRecordSource.d.ts +28 -0
  63. package/lib/relay/RelayRecordSource.js +75 -0
  64. package/lib/relay/RelayRecordSourceMutator.d.ts +36 -0
  65. package/lib/relay/RelayRecordSourceMutator.js +80 -0
  66. package/lib/relay/RelayRecordSourceProxy.d.ts +25 -0
  67. package/lib/relay/RelayRecordSourceProxy.js +57 -0
  68. package/lib/relay/RelayReferenceMarker.d.ts +10 -0
  69. package/lib/relay/RelayReferenceMarker.js +60 -0
  70. package/lib/relay/RelayStoreProvider.d.ts +7 -0
  71. package/lib/relay/RelayStoreProvider.js +22 -0
  72. package/lib/relay/RelayStoreUtils.d.ts +51 -0
  73. package/lib/relay/RelayStoreUtils.js +208 -0
  74. package/lib/relay/RelayTypes.d.ts +92 -0
  75. package/lib/relay/RelayTypes.js +5 -0
  76. package/lib/relay/queries.d.ts +86 -0
  77. package/lib/relay/queries.js +73 -0
  78. package/lib/umd/relay-forms-nodeps.js +1478 -0
  79. package/lib/umd/relay-forms-nodeps.js.map +1 -0
  80. package/lib/umd/relay-forms-nodeps.min.js +2 -0
  81. package/lib/umd/relay-forms-nodeps.min.js.map +1 -0
  82. package/lib/useForceUpdate.d.ts +1 -0
  83. package/lib/useForceUpdate.js +14 -0
  84. package/lib/useFormSetValue.d.ts +2 -0
  85. package/lib/useFormSetValue.js +90 -0
  86. package/lib/useFormState.d.ts +2 -0
  87. package/lib/useFormState.js +54 -0
  88. package/lib/useFormSubmit.d.ts +2 -0
  89. package/lib/useFormSubmit.js +110 -0
  90. package/lib/useFormValue.d.ts +2 -0
  91. package/lib/useFormValue.js +25 -0
  92. package/package.json +89 -0
  93. package/replace.config.js +5 -0
  94. package/rollup.config.js +92 -0
  95. package/tsconfig.esm.json +7 -0
  96. package/yarn-error.log +127 -0
@@ -0,0 +1,1478 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["relay-forms-nodeps"] = {}, global.React));
5
+ })(this, (function (exports, React) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
10
+
11
+ var ReactRelayContext = React__default["default"].createContext(null);
12
+ var StoreProvider = function (props) {
13
+ var context = React__default["default"].useMemo(function () {
14
+ return {
15
+ store: props.store
16
+ };
17
+ }, [props.store]);
18
+ return React__default["default"].createElement(ReactRelayContext.Provider, {
19
+ value: context
20
+ }, props.children);
21
+ };
22
+ function useStore() {
23
+ var store = React__default["default"].useContext(ReactRelayContext).store;
24
+ return store;
25
+ }
26
+
27
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
28
+ /**
29
+ * Copyright (c) Facebook, Inc. and its affiliates.
30
+ *
31
+ * This source code is licensed under the MIT license found in the
32
+ * LICENSE file in the root directory of this source tree.
33
+ *
34
+ * @flow
35
+ * @format
36
+ */
37
+ function isPromise(p) {
38
+ return !!p && typeof p.then === 'function';
39
+ }
40
+ /**
41
+ * Copyright (c) 2013-present, Facebook, Inc.
42
+ *
43
+ * This source code is licensed under the MIT license found in the
44
+ * LICENSE file in the root directory of this source tree.
45
+ *
46
+ *
47
+ */
48
+ var aStackPool = [];
49
+ var bStackPool = [];
50
+ /**
51
+ * Checks if two values are equal. Values may be primitives, arrays, or objects.
52
+ * Returns true if both arguments have the same keys and values.
53
+ *
54
+ * @see http://underscorejs.org
55
+ * @copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
56
+ * @license MIT
57
+ */
58
+ function areEqual(a, b) {
59
+ var aStack = aStackPool.length ? aStackPool.pop() : [];
60
+ var bStack = bStackPool.length ? bStackPool.pop() : [];
61
+ var result = eq(a, b, aStack, bStack);
62
+ aStack.length = 0;
63
+ bStack.length = 0;
64
+ aStackPool.push(aStack);
65
+ bStackPool.push(bStack);
66
+ return result;
67
+ }
68
+ function eq(a, b, aStack, bStack) {
69
+ if (a === b) {
70
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
71
+ return a !== 0 || 1 / a == 1 / b;
72
+ }
73
+ if (a == null || b == null) {
74
+ // a or b can be `null` or `undefined`
75
+ return false;
76
+ }
77
+ if (typeof a != 'object' || typeof b != 'object') {
78
+ return false;
79
+ }
80
+ var objToStr = Object.prototype.toString;
81
+ var className = objToStr.call(a);
82
+ if (className != objToStr.call(b)) {
83
+ return false;
84
+ }
85
+ switch (className) {
86
+ case '[object String]':
87
+ return a == String(b);
88
+ case '[object Number]':
89
+ return isNaN(a) || isNaN(b) ? false : a == Number(b);
90
+ case '[object Date]':
91
+ case '[object Boolean]':
92
+ return +a == +b;
93
+ case '[object RegExp]':
94
+ return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase;
95
+ } // Assume equality for cyclic structures.
96
+ var length = aStack.length;
97
+ // eslint-disable-next-line no-plusplus
98
+ while (length--) {
99
+ if (aStack[length] == a) {
100
+ return bStack[length] == b;
101
+ }
102
+ }
103
+ aStack.push(a);
104
+ bStack.push(b);
105
+ var size = 0; // Recursively compare objects and arrays.
106
+ if (className === '[object Array]') {
107
+ size = a.length;
108
+ if (size !== b.length) {
109
+ return false;
110
+ } // Deep compare the contents, ignoring non-numeric properties.
111
+ // eslint-disable-next-line no-plusplus
112
+ while (size--) {
113
+ if (!eq(a[size], b[size], aStack, bStack)) {
114
+ return false;
115
+ }
116
+ }
117
+ } else {
118
+ if (a.constructor !== b.constructor) {
119
+ return false;
120
+ }
121
+ if (a.hasOwnProperty('valueOf') && b.hasOwnProperty('valueOf')) {
122
+ return a.valueOf() == b.valueOf();
123
+ }
124
+ var keys = Object.keys(a);
125
+ if (keys.length != Object.keys(b).length) {
126
+ return false;
127
+ }
128
+ for (var i = 0; i < keys.length; i++) {
129
+ if (!eq(a[keys[i]], b[keys[i]], aStack, bStack)) {
130
+ return false;
131
+ }
132
+ }
133
+ }
134
+ aStack.pop();
135
+ bStack.pop();
136
+ return true;
137
+ }
138
+ /**
139
+ * Constants shared by all implementations of RecordSource/MutableRecordSource/etc.
140
+ */
141
+ var RelayStoreUtils = {
142
+ ID_KEY: '__id',
143
+ REF_KEY: '__ref',
144
+ REFS_KEY: '__refs',
145
+ ROOT_ID: 'client:root'
146
+ };
147
+ var RelayRecordState;
148
+ (function (RelayRecordState) {
149
+ /**
150
+ * Record exists (either fetched from the server or produced by a local,
151
+ * optimistic update).
152
+ */
153
+ RelayRecordState["EXISTENT"] = "EXISTENT";
154
+ /**
155
+ * Record is known not to exist (either as the result of a mutation, or
156
+ * because the server returned `null` when queried for the record).
157
+ */
158
+ RelayRecordState["NONEXISTENT"] = "NONEXISTENT";
159
+ /**
160
+ * Record State is unknown because it has not yet been fetched from the
161
+ * server.
162
+ */
163
+ RelayRecordState["UNKNOWN"] = "UNKNOWN";
164
+ })(RelayRecordState || (RelayRecordState = {}));
165
+ var LINKED_FIELD = 'LinkedField';
166
+ //const hasWeakSetDefined = typeof WeakSet !== 'undefined';
167
+ //const hasWeakMapDefined = typeof WeakMap !== 'undefined';
168
+ function checkRecycleData(data) {
169
+ return typeof data !== 'object' || data instanceof Set || data instanceof Map ||
170
+ //(hasWeakSetDefined && nextData instanceof WeakSet) ||
171
+ //(hasWeakMapDefined && nextData instanceof WeakMap) ||
172
+ !data;
173
+ }
174
+ /**
175
+ * Recycles subtrees from `prevData` by replacing equal subtrees in `nextData`.
176
+ */
177
+ function recycleNodesInto(prevData, nextData) {
178
+ if (prevData === nextData || checkRecycleData(prevData) || checkRecycleData(nextData)) {
179
+ return nextData;
180
+ }
181
+ var canRecycle = false;
182
+ // Assign local variables to preserve Flow type refinement.
183
+ var prevArray = Array.isArray(prevData) ? prevData : null;
184
+ var nextArray = Array.isArray(nextData) ? nextData : null;
185
+ if (prevArray && nextArray) {
186
+ canRecycle = nextArray.reduce(function (wasEqual, nextItem, ii) {
187
+ var prevValue = prevArray[ii];
188
+ var nextValue = recycleNodesInto(prevValue, nextItem);
189
+ if (nextValue !== nextArray[ii]) {
190
+ nextArray[ii] = nextValue;
191
+ }
192
+ return wasEqual && nextValue === prevArray[ii];
193
+ }, true) && prevArray.length === nextArray.length;
194
+ } else if (!prevArray && !nextArray) {
195
+ // Assign local variables to preserve Flow type refinement.
196
+ var prevObject_1 = prevData;
197
+ var nextObject_1 = nextData;
198
+ var prevKeys = Object.keys(prevObject_1);
199
+ var nextKeys = Object.keys(nextObject_1);
200
+ canRecycle = nextKeys.reduce(function (wasEqual, key) {
201
+ var prevValue = prevObject_1[key];
202
+ var nextValue = recycleNodesInto(prevValue, nextObject_1[key]);
203
+ if (nextValue !== nextObject_1[key]) {
204
+ nextObject_1[key] = nextValue;
205
+ }
206
+ return wasEqual && nextValue === prevObject_1[key];
207
+ }, true) && prevKeys.length === nextKeys.length;
208
+ }
209
+ return canRecycle ? prevData : nextData;
210
+ }
211
+ var ITERATOR_KEY = Symbol.iterator;
212
+ function hasOverlappingIDs(seenRecords, updatedRecordIDs) {
213
+ // $FlowFixMe: Set is an iterable type, accessing its iterator is allowed.
214
+ var iterator = seenRecords[ITERATOR_KEY]();
215
+ var next = iterator.next();
216
+ while (!next.done) {
217
+ var key = next.value;
218
+ if (updatedRecordIDs.has(key)) {
219
+ return true;
220
+ }
221
+ next = iterator.next();
222
+ }
223
+ return false;
224
+ }
225
+
226
+ function useForceUpdate() {
227
+ var _a = React.useReducer(function (x) {
228
+ return x + 1;
229
+ }, 0),
230
+ forceUpdate = _a[1];
231
+ return forceUpdate;
232
+ }
233
+
234
+ var id = {
235
+ name: 'id'
236
+ };
237
+ var key = {
238
+ name: 'key'
239
+ };
240
+ var check = {
241
+ name: 'check'
242
+ };
243
+ var error = {
244
+ name: 'error'
245
+ };
246
+ var value = {
247
+ name: 'value'
248
+ };
249
+ var kindFragment = 'Fragment';
250
+ var QueryErrors = {
251
+ id: '1',
252
+ fragment: {
253
+ kind: kindFragment,
254
+ name: 'queryErrors',
255
+ selections: [{
256
+ kind: LINKED_FIELD,
257
+ name: 'form',
258
+ plural: false,
259
+ selections: [{
260
+ name: 'isSubmitting'
261
+ }, {
262
+ name: 'isValidating'
263
+ }, {
264
+ kind: LINKED_FIELD,
265
+ name: 'entries',
266
+ plural: true,
267
+ selections: [id, key, error, check]
268
+ }]
269
+ }] /*: any*/
270
+ }
271
+ };
272
+
273
+ var QueryFields = {
274
+ id: '0',
275
+ fragment: {
276
+ kind: kindFragment,
277
+ name: 'queryFields',
278
+ selections: [{
279
+ kind: LINKED_FIELD,
280
+ name: 'form',
281
+ plural: false,
282
+ selections: [{
283
+ kind: LINKED_FIELD,
284
+ name: 'entries',
285
+ plural: true,
286
+ selections: [id, key, value, error, check]
287
+ }]
288
+ }]
289
+ }
290
+ };
291
+ var FragmentSet = {
292
+ kind: kindFragment,
293
+ name: 'fragmentSet',
294
+ selections: [id, check]
295
+ };
296
+ var FragmentValue = {
297
+ kind: kindFragment,
298
+ name: 'fragmentValue',
299
+ selections: [id, value, error]
300
+ };
301
+
302
+ /**
303
+ * Copyright (c) Facebook, Inc. and its affiliates.
304
+ *
305
+ * This source code is licensed under the MIT license found in the
306
+ * LICENSE file in the root directory of this source tree.
307
+ *
308
+ * @flow strict-local
309
+ * @format
310
+ */
311
+ var ID_KEY$1 = RelayStoreUtils.ID_KEY;
312
+ function createReaderSelector(node, dataID) {
313
+ return {
314
+ //kind: 'SingularReaderSelector',
315
+ dataID: dataID,
316
+ node: node
317
+ };
318
+ }
319
+ function getSingularSelector(fragment, item) {
320
+ return createReaderSelector(fragment, item[ID_KEY$1]);
321
+ }
322
+ function createOperationDescriptor(request) {
323
+ var operationDescriptor = {
324
+ fragment: createReaderSelector(request.fragment, RelayStoreUtils.ROOT_ID),
325
+ identifier: request.identifier
326
+ };
327
+ return operationDescriptor;
328
+ }
329
+
330
+ var PREFIX_LOCAL_FORM = 'local:form';
331
+ var internalCommitLocalUpdate = function (environment, updater) {
332
+ environment.commitUpdate(function (store) {
333
+ var localForm = store.get(PREFIX_LOCAL_FORM);
334
+ if (!localForm) {
335
+ localForm = store.create(PREFIX_LOCAL_FORM).setLinkedRecords([], 'entries');
336
+ store.getRoot().setLinkedRecord(localForm, 'form');
337
+ }
338
+ updater(store, localForm);
339
+ });
340
+ };
341
+ function getFieldId(key) {
342
+ return PREFIX_LOCAL_FORM + '.' + key;
343
+ }
344
+ function getSnapshot(environment, fragment, key) {
345
+ var item = {
346
+ __id: getFieldId(key)
347
+ };
348
+ return environment.lookup(getSingularSelector(fragment, item));
349
+ }
350
+ var commitResetIntoRelay = function (entries, environment) {
351
+ internalCommitLocalUpdate(environment, function (store, form) {
352
+ form.setValue(false, 'isSubmitting');
353
+ form.setValue(false, 'isValidating');
354
+ entries.forEach(function (entry) {
355
+ return store.get(getFieldId(entry.key)).setValue('RESET', 'check');
356
+ });
357
+ });
358
+ };
359
+ var commitValidateIntoRelay = function (entries, isSubmitting, environment) {
360
+ internalCommitLocalUpdate(environment, function (store, form) {
361
+ form.setValue(isSubmitting, 'isSubmitting');
362
+ form.setValue(true, 'isValidating');
363
+ entries.forEach(function (entry) {
364
+ return store.get(getFieldId(entry.key)).setValue('START', 'check');
365
+ });
366
+ });
367
+ };
368
+ var commitSubmitEndRelay = function (environment) {
369
+ internalCommitLocalUpdate(environment, function (_, form) {
370
+ form.setValue(false, 'isSubmitting');
371
+ });
372
+ };
373
+ var commitValidateEndRelay = function (environment) {
374
+ internalCommitLocalUpdate(environment, function (_, form) {
375
+ form.setValue(false, 'isValidating');
376
+ });
377
+ };
378
+ var commitResetField = function (environment, key) {
379
+ var id = getFieldId(key);
380
+ internalCommitLocalUpdate(environment, function (store, form) {
381
+ var entriesArray = form.getLinkedRecords('entries');
382
+ var newEntries = entriesArray.filter(function (value) {
383
+ return value.getDataID() != id;
384
+ });
385
+ form.setLinkedRecords(newEntries, 'entries');
386
+ store.delete(id);
387
+ });
388
+ };
389
+ var commitValue = function (key, value, check, environment) {
390
+ var id = getFieldId(key);
391
+ internalCommitLocalUpdate(environment, function (store, form) {
392
+ var field = store.get(id);
393
+ if (!field) {
394
+ field = store.create(id);
395
+ var entriesArray = form.getLinkedRecords('entries');
396
+ entriesArray.push(field);
397
+ form.setLinkedRecords(entriesArray, 'entries');
398
+ }
399
+ field.setValue(id, 'id').setValue(key, 'key').setValue(check, 'check').setValue(value, 'value');
400
+ });
401
+ };
402
+ var commitErrorIntoRelay = function (key, error, environment) {
403
+ internalCommitLocalUpdate(environment, function (store) {
404
+ store.get(getFieldId(key)).setValue(error, 'error').setValue('DONE', 'check');
405
+ });
406
+ };
407
+ var operationQueryForm = createOperationDescriptor(QueryFields);
408
+ var operationQueryErrorsForm = createOperationDescriptor(QueryErrors);
409
+
410
+ var useFormState = function () {
411
+ var ref = React__default["default"].useRef({
412
+ errors: undefined,
413
+ isValidating: false,
414
+ isSubmitting: false,
415
+ isValid: false
416
+ });
417
+ var forceUpdate = useForceUpdate();
418
+ var environment = useStore();
419
+ React__default["default"].useEffect(function () {
420
+ function checkError(s) {
421
+ var data = s.data;
422
+ var form = data.form;
423
+ var entries = form.entries;
424
+ var current = ref.current;
425
+ var entryErrors = entries.filter(function (value) {
426
+ return !!value.error;
427
+ });
428
+ var entryValidated = entries.filter(function (value) {
429
+ return value.check === 'DONE';
430
+ });
431
+ var errors = entryErrors.length > 0 ? entryErrors : undefined;
432
+ var isValidating = form.isValidating;
433
+ var isSubmitting = form.isSubmitting;
434
+ var isValid = entries.length === entryValidated.length && (!errors || Object.keys(errors).length === 0);
435
+ var newState = {
436
+ errors: errors,
437
+ isValid: isValid,
438
+ isValidating: isValidating,
439
+ isSubmitting: isSubmitting
440
+ };
441
+ if (!areEqual(current, newState)) {
442
+ ref.current = newState;
443
+ forceUpdate();
444
+ }
445
+ }
446
+ var snapshot = environment.lookup(operationQueryErrorsForm.fragment);
447
+ checkError(snapshot);
448
+ return environment.subscribe(snapshot, function (s) {
449
+ checkError(s);
450
+ }).dispose;
451
+ }, [environment, forceUpdate]);
452
+ return ref.current;
453
+ };
454
+
455
+ var useFormSubmit = function (_a) {
456
+ var onSubmit = _a.onSubmit;
457
+ var environment = useStore();
458
+ React__default["default"].useEffect(function () {
459
+ return environment.retain(operationQueryForm).dispose;
460
+ }, [environment]);
461
+ var ref = React__default["default"].useRef({
462
+ isSubmitting: false,
463
+ isValidating: false,
464
+ error: undefined,
465
+ subscription: undefined
466
+ });
467
+ var internalValidate = React__default["default"].useCallback(function (snapshot, isSubmitting) {
468
+ ref.current.isValidating = true;
469
+ var data = snapshot.data;
470
+ var filtered = data.form.entries.filter(function (value) {
471
+ return value.check === 'INIT';
472
+ });
473
+ commitValidateIntoRelay(filtered, isSubmitting, environment);
474
+ }, [environment]);
475
+ var execute = React__default["default"].useCallback(function (environment, snapshot, dispose, onSubmit) {
476
+ var data = snapshot.data;
477
+ var entries = data.form.entries;
478
+ var filtered = entries.filter(function (value) {
479
+ return value.check === 'DONE';
480
+ });
481
+ if (filtered.length === entries.length) {
482
+ var errors = entries.filter(function (value) {
483
+ return !!value.error;
484
+ });
485
+ commitValidateEndRelay(environment);
486
+ ref.current.isValidating = false;
487
+ var internalDispose = function () {
488
+ dispose();
489
+ if (ref.current.isSubmitting) {
490
+ ref.current.isSubmitting = false;
491
+ commitSubmitEndRelay(environment);
492
+ }
493
+ };
494
+ if (ref.current.isSubmitting && onSubmit && errors.length === 0) {
495
+ var result_1 = {};
496
+ entries.forEach(function (entry) {
497
+ result_1[entry.key] = entry.value;
498
+ });
499
+ var submit_1 = onSubmit(result_1);
500
+ if (isPromise(submit_1)) {
501
+ submit_1.then(internalDispose).catch(internalDispose);
502
+ return;
503
+ }
504
+ }
505
+ internalDispose();
506
+ }
507
+ }, []);
508
+ var reset = React__default["default"].useCallback(function () {
509
+ var snapshot = environment.lookup(operationQueryForm.fragment);
510
+ if (ref.current.isValidating && ref.current.isSubmitting) {
511
+ return;
512
+ }
513
+ var data = snapshot.data;
514
+ commitResetIntoRelay(data.form.entries, environment);
515
+ }, [environment]);
516
+ var subscribe = React__default["default"].useCallback(function (submit) {
517
+ if (submit === void 0) {
518
+ submit = false;
519
+ }
520
+ var snapshot = environment.lookup(operationQueryForm.fragment);
521
+ var subscription = ref.current.subscription;
522
+ subscription && subscription.dispose();
523
+ function dispose() {
524
+ subscription && subscription.dispose();
525
+ ref.current.subscription = null;
526
+ }
527
+ ref.current.subscription = environment.subscribe(snapshot, function (s) {
528
+ return execute(environment, s, dispose, onSubmit);
529
+ });
530
+ internalValidate(snapshot, submit);
531
+ execute(environment, snapshot, dispose, onSubmit);
532
+ }, [environment, internalValidate, execute, onSubmit]);
533
+ var validate = React__default["default"].useCallback(function () {
534
+ if (!ref.current.isValidating) {
535
+ subscribe(false);
536
+ }
537
+ }, [subscribe]);
538
+ var submit = React__default["default"].useCallback(function (event) {
539
+ if (event) {
540
+ event.preventDefault();
541
+ }
542
+ if (!ref.current.isSubmitting) {
543
+ ref.current.isSubmitting = true;
544
+ subscribe(true);
545
+ }
546
+ }, [subscribe]);
547
+ var result = React__default["default"].useMemo(function () {
548
+ return {
549
+ submit: submit,
550
+ validate: validate,
551
+ reset: reset
552
+ };
553
+ }, [submit, validate, reset]);
554
+ return result;
555
+ };
556
+
557
+ function useFormSetValue(_a) {
558
+ var key = _a.key,
559
+ initialValue = _a.initialValue,
560
+ validate = _a.validate,
561
+ validateOnChange = _a.validateOnChange;
562
+ var forceUpdate = useForceUpdate();
563
+ var environment = useStore();
564
+ var ref = React__default["default"].useRef({
565
+ value: initialValue,
566
+ error: undefined,
567
+ check: validate ? 'INIT' : 'DONE',
568
+ isChecking: false
569
+ });
570
+ var setValue = React__default["default"].useCallback(function (newValue) {
571
+ ref.current.value = newValue;
572
+ if (ref.current.check === 'DONE' && validate) {
573
+ ref.current.check = 'START';
574
+ }
575
+ commitValue(key, newValue, ref.current.check, environment);
576
+ forceUpdate();
577
+ }, [environment, key, validate, forceUpdate]);
578
+ React__default["default"].useEffect(function () {
579
+ //commitResetField(environment, key);
580
+ commitValue(key, initialValue, ref.current.check, environment);
581
+ var snapshot = getSnapshot(environment, FragmentSet, key);
582
+ var disposeSubscrition = environment.subscribe(snapshot, function (s) {
583
+ var check = s.data.check;
584
+ var isStart = check === 'START';
585
+ var isReset = check === 'RESET';
586
+ ref.current.check = check;
587
+ if (isReset) {
588
+ ref.current.check = validate ? 'INIT' : 'DONE';
589
+ setValue(initialValue);
590
+ } else {
591
+ if (!validate) {
592
+ commitErrorIntoRelay(key, undefined, environment);
593
+ return;
594
+ }
595
+ if (isStart && !ref.current.isChecking) {
596
+ internalValidate(ref.current.value);
597
+ }
598
+ }
599
+ }).dispose;
600
+ var dispose = function () {
601
+ disposeSubscrition();
602
+ commitResetField(environment, key);
603
+ };
604
+ function finalizeCheck(error) {
605
+ ref.current.isChecking = false;
606
+ if (ref.current.error !== error) {
607
+ ref.current.error = error;
608
+ forceUpdate();
609
+ }
610
+ commitErrorIntoRelay(key, error, environment);
611
+ }
612
+ function internalValidate(value) {
613
+ ref.current.isChecking = true;
614
+ var result = validate(value);
615
+ function internalFinalize(error) {
616
+ if (value !== ref.current.value) {
617
+ internalValidate(ref.current.value);
618
+ return;
619
+ }
620
+ finalizeCheck(error);
621
+ }
622
+ if (isPromise(result)) {
623
+ result.then(internalFinalize).catch(internalFinalize);
624
+ } else {
625
+ internalFinalize(result);
626
+ }
627
+ }
628
+ if (validateOnChange) {
629
+ internalValidate(initialValue);
630
+ }
631
+ return dispose;
632
+ }, [environment, initialValue, key, setValue, validate, validateOnChange, forceUpdate]);
633
+ return [ref.current, setValue];
634
+ }
635
+
636
+ function useFormValue(key) {
637
+ var environment = useStore();
638
+ var snapshot = React__default["default"].useMemo(function () {
639
+ return getSnapshot(environment, FragmentValue, key);
640
+ }, [key, environment]);
641
+ var _a = React__default["default"].useState(snapshot.data),
642
+ data = _a[0],
643
+ setData = _a[1];
644
+ React__default["default"].useEffect(function () {
645
+ return environment.subscribe(snapshot, function (s) {
646
+ setData(s.data);
647
+ }).dispose;
648
+ }, [environment, snapshot, setData]);
649
+ return data;
650
+ }
651
+
652
+ /*! *****************************************************************************
653
+ Copyright (c) Microsoft Corporation.
654
+
655
+ Permission to use, copy, modify, and/or distribute this software for any
656
+ purpose with or without fee is hereby granted.
657
+
658
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
659
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
660
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
661
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
662
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
663
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
664
+ PERFORMANCE OF THIS SOFTWARE.
665
+ ***************************************************************************** */
666
+
667
+ var __assign = function() {
668
+ __assign = Object.assign || function __assign(t) {
669
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
670
+ s = arguments[i];
671
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
672
+ }
673
+ return t;
674
+ };
675
+ return __assign.apply(this, arguments);
676
+ };
677
+
678
+ function __generator(thisArg, body) {
679
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
680
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
681
+ function verb(n) { return function (v) { return step([n, v]); }; }
682
+ function step(op) {
683
+ if (f) throw new TypeError("Generator is already executing.");
684
+ while (_) try {
685
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
686
+ if (y = 0, t) op = [op[0] & 2, t.value];
687
+ switch (op[0]) {
688
+ case 0: case 1: t = op; break;
689
+ case 4: _.label++; return { value: op[1], done: false };
690
+ case 5: _.label++; y = op[1]; op = [0]; continue;
691
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
692
+ default:
693
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
694
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
695
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
696
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
697
+ if (t[2]) _.ops.pop();
698
+ _.trys.pop(); continue;
699
+ }
700
+ op = body.call(thisArg, _);
701
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
702
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
703
+ }
704
+ }
705
+
706
+ var ID_KEY = RelayStoreUtils.ID_KEY,
707
+ REF_KEY = RelayStoreUtils.REF_KEY,
708
+ REFS_KEY = RelayStoreUtils.REFS_KEY;
709
+ /**
710
+ * @public
711
+ *
712
+ * Low-level record manipulation methods.
713
+ *
714
+ * A note about perf: we use long-hand property access rather than computed
715
+ * properties in this file for speed ie.
716
+ *
717
+ * const object = {};
718
+ * object[KEY] = value;
719
+ * record[storageKey] = object;
720
+ *
721
+ * instead of:
722
+ *
723
+ * record[storageKey] = {
724
+ * [KEY]: value,
725
+ * };
726
+ *
727
+ * The latter gets transformed by Babel into something like:
728
+ *
729
+ * function _defineProperty(obj, key, value) {
730
+ * if (key in obj) {
731
+ * Object.defineProperty(obj, key, {
732
+ * value: value,
733
+ * enumerable: true,
734
+ * configurable: true,
735
+ * writable: true,
736
+ * });
737
+ * } else {
738
+ * obj[key] = value;
739
+ * }
740
+ * return obj;
741
+ * }
742
+ *
743
+ * record[storageKey] = _defineProperty({}, KEY, value);
744
+ *
745
+ * A quick benchmark shows that computed property access is an order of
746
+ * magnitude slower (times in seconds for 100,000 iterations):
747
+ *
748
+ * best avg sd
749
+ * computed 0.02175 0.02292 0.00113
750
+ * manual 0.00110 0.00123 0.00008
751
+ */
752
+ /**
753
+ * @public
754
+ *
755
+ * Create a new record.
756
+ */
757
+ function create(dataID) {
758
+ // See perf note above for why we aren't using computed property access.
759
+ var record = {};
760
+ record[ID_KEY] = dataID;
761
+ return record;
762
+ }
763
+ /**
764
+ * @public
765
+ *
766
+ * Get a scalar (non-link) field value.
767
+ */
768
+ function getValue(record, storageKey) {
769
+ return record[storageKey];
770
+ }
771
+ /**
772
+ * @private
773
+ *
774
+ * Get the value of a field as a reference to another record. Throws if the
775
+ * field has a different type.
776
+ */
777
+ function getLinkedRecordKey(record, storageKey, key) {
778
+ var link = record[storageKey];
779
+ if (link == null) {
780
+ return link;
781
+ }
782
+ return link[key];
783
+ }
784
+ /**
785
+ * @public
786
+ *
787
+ * Get the value of a field as a reference to another record. Throws if the
788
+ * field has a different type.
789
+ */
790
+ function getLinkedRecordID(record, storageKey) {
791
+ return getLinkedRecordKey(record, storageKey, REF_KEY);
792
+ }
793
+ /**
794
+ * @public
795
+ *
796
+ * Get the value of a field as a list of references to other records. Throws if
797
+ * the field has a different type.
798
+ */
799
+ function getLinkedRecordIDs(record, storageKey) {
800
+ return getLinkedRecordKey(record, storageKey, REFS_KEY);
801
+ }
802
+ /**
803
+ * @public
804
+ *
805
+ * Compares the fields of a previous and new record, returning either the
806
+ * previous record if all fields are equal or a new record (with merged fields)
807
+ * if any fields have changed.
808
+ */
809
+ function update(prevRecord, nextRecord) {
810
+ var updated = null;
811
+ var keys = Object.keys(nextRecord);
812
+ for (var ii = 0; ii < keys.length; ii++) {
813
+ var key = keys[ii];
814
+ if (updated || !areEqual(prevRecord[key], nextRecord[key])) {
815
+ updated = updated !== null ? updated : __assign({}, prevRecord);
816
+ updated[key] = nextRecord[key];
817
+ }
818
+ }
819
+ return updated !== null ? updated : prevRecord;
820
+ }
821
+ /**
822
+ * @public
823
+ *
824
+ * Set the value of a storageKey to a scalar.
825
+ * YES
826
+ */
827
+ function setValue(record, storageKey, value) {
828
+ record[storageKey] = value;
829
+ }
830
+ /**
831
+ * @private
832
+ *
833
+ * Get the value of a field as a reference to another record. Throws if the
834
+ * field has a different type.
835
+ */
836
+ function setLinkedRecordKey(record, storageKey, linkedID, key) {
837
+ // See perf note above for why we aren't using computed property access.
838
+ var link = {};
839
+ link[key] = linkedID;
840
+ record[storageKey] = link;
841
+ }
842
+ /**
843
+ * @public
844
+ *
845
+ * Set the value of a field to a reference to another record.
846
+ */
847
+ function setLinkedRecordID(record, storageKey, linkedID) {
848
+ setLinkedRecordKey(record, storageKey, linkedID, REF_KEY);
849
+ }
850
+ /**
851
+ * @public
852
+ *
853
+ * Set the value of a field to a list of references other records.
854
+ */
855
+ function setLinkedRecordIDs(record, storageKey, linkedIDs) {
856
+ setLinkedRecordKey(record, storageKey, linkedIDs, REFS_KEY);
857
+ }
858
+ var RelayModernRecord = {
859
+ create: create,
860
+ getLinkedRecordID: getLinkedRecordID,
861
+ getLinkedRecordIDs: getLinkedRecordIDs,
862
+ getValue: getValue,
863
+ setValue: setValue,
864
+ setLinkedRecordID: setLinkedRecordID,
865
+ setLinkedRecordIDs: setLinkedRecordIDs,
866
+ update: update
867
+ };
868
+
869
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
870
+ function relayRead(recordSource, selector) {
871
+ var reader = new RelayReader(recordSource, selector);
872
+ return reader.read();
873
+ }
874
+ /**
875
+ * @private
876
+ */
877
+ var RelayReader = /** @class */function () {
878
+ function RelayReader(recordSource, selector) {
879
+ this._recordSource = recordSource;
880
+ this._seenRecords = new Set();
881
+ this._selector = selector;
882
+ }
883
+ RelayReader.prototype.read = function () {
884
+ var _a = this._selector,
885
+ node = _a.node,
886
+ dataID = _a.dataID;
887
+ var data = this._traverse(node, dataID, null);
888
+ return {
889
+ data: data,
890
+ seenRecords: this._seenRecords,
891
+ selector: this._selector
892
+ };
893
+ };
894
+ RelayReader.prototype._traverse = function (node, dataID, prevData) {
895
+ if (dataID == null) {
896
+ return dataID;
897
+ }
898
+ var record = this._recordSource.get(dataID);
899
+ this._seenRecords.add(dataID);
900
+ if (record == null) {
901
+ return record;
902
+ }
903
+ var data = prevData || {};
904
+ this._traverseSelections(node.selections, record, data);
905
+ return data;
906
+ };
907
+ RelayReader.prototype._traverseSelections = function (selections, record, data) {
908
+ var _this = this;
909
+ var _loop_1 = function (i) {
910
+ var selection = selections[i];
911
+ var name_1 = selection.name;
912
+ var prevData = data[name_1];
913
+ var value = null;
914
+ if (selection.kind == LINKED_FIELD) {
915
+ if (selection.plural) {
916
+ var ids = RelayModernRecord.getLinkedRecordIDs(record, name_1);
917
+ if (ids != null) {
918
+ var linkedArray_1 = prevData || [];
919
+ ids.forEach(function (linkedID, nextIndex) {
920
+ var prevItem = linkedArray_1[nextIndex];
921
+ linkedArray_1[nextIndex] = _this._traverse(selection, linkedID, prevItem);
922
+ });
923
+ value = linkedArray_1;
924
+ }
925
+ } else {
926
+ var id = RelayModernRecord.getLinkedRecordID(record, name_1);
927
+ value = this_1._traverse(selection, id, prevData);
928
+ }
929
+ } else {
930
+ // relay-forms, now default scalar
931
+ value = RelayModernRecord.getValue(record, name_1);
932
+ //this._readScalar(selection, record, data);
933
+ }
934
+
935
+ data[name_1] = value;
936
+ };
937
+ var this_1 = this;
938
+ for (var i = 0; i < selections.length; i++) {
939
+ _loop_1(i);
940
+ }
941
+ };
942
+ return RelayReader;
943
+ }();
944
+
945
+ /**
946
+ * Copyright (c) Facebook, Inc. and its affiliates.
947
+ *
948
+ * This source code is licensed under the MIT license found in the
949
+ * LICENSE file in the root directory of this source tree.
950
+ *
951
+ * @flow strict-local
952
+ * @format
953
+ */
954
+ var EXISTENT = RelayRecordState.EXISTENT,
955
+ NONEXISTENT = RelayRecordState.NONEXISTENT,
956
+ UNKNOWN = RelayRecordState.UNKNOWN;
957
+ /**
958
+ * An implementation of the `MutableRecordSource` interface (defined in
959
+ * `RelayStoreTypes`) that holds all records in memory (JS Map).
960
+ */
961
+ var RelayRecordSource = /** @class */function () {
962
+ function RelayRecordSource(records) {
963
+ var _this = this;
964
+ this._records = new Map();
965
+ if (records != null) {
966
+ Object.keys(records).forEach(function (key) {
967
+ _this._records.set(key, records[key]);
968
+ });
969
+ }
970
+ }
971
+ RelayRecordSource.prototype.clear = function () {
972
+ this._records = new Map();
973
+ };
974
+ RelayRecordSource.prototype.delete = function (dataID) {
975
+ this._records.set(dataID, null);
976
+ };
977
+ RelayRecordSource.prototype.get = function (dataID) {
978
+ return this._records.get(dataID);
979
+ };
980
+ RelayRecordSource.prototype.getRecordIDs = function () {
981
+ return Array.from(this._records.keys());
982
+ };
983
+ RelayRecordSource.prototype.getStatus = function (dataID) {
984
+ if (!this._records.has(dataID)) {
985
+ return UNKNOWN;
986
+ }
987
+ return this._records.get(dataID) == null ? NONEXISTENT : EXISTENT;
988
+ };
989
+ RelayRecordSource.prototype.has = function (dataID) {
990
+ return this._records.has(dataID);
991
+ };
992
+ RelayRecordSource.prototype.remove = function (dataID) {
993
+ this._records.delete(dataID);
994
+ };
995
+ RelayRecordSource.prototype.set = function (dataID, record) {
996
+ this._records.set(dataID, record);
997
+ };
998
+ RelayRecordSource.prototype.size = function () {
999
+ return this._records.size;
1000
+ };
1001
+ RelayRecordSource.prototype.toJSON = function () {
1002
+ var obj = {};
1003
+ for (var _i = 0, _a = this._records.entries(); _i < _a.length; _i++) {
1004
+ var _b = _a[_i],
1005
+ key = _b[0],
1006
+ value = _b[1];
1007
+ obj[key] = value;
1008
+ }
1009
+ return obj;
1010
+ };
1011
+ return RelayRecordSource;
1012
+ }();
1013
+
1014
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1015
+ /**
1016
+ * @internal
1017
+ *
1018
+ * Wrapper API that is an amalgam of the `RelayModernRecord` API and
1019
+ * `MutableRecordSource` interface, implementing copy-on-write semantics for records
1020
+ * in a record source.
1021
+ *
1022
+ * Modifications are applied to fresh copies of records:
1023
+ * - Records in `base` are never modified.
1024
+ * - Modifications cause a fresh version of a record to be created in `sink`.
1025
+ * These sink records contain only modified fields.
1026
+ */
1027
+ var RelayRecordSourceMutator = /** @class */function () {
1028
+ function RelayRecordSourceMutator(base, sink) {
1029
+ this.__sources = [sink, base];
1030
+ this._base = base;
1031
+ this._sink = sink;
1032
+ }
1033
+ RelayRecordSourceMutator.prototype._getSinkRecord = function (dataID) {
1034
+ var sinkRecord = this._sink.get(dataID);
1035
+ if (!sinkRecord) {
1036
+ sinkRecord = RelayModernRecord.create(dataID);
1037
+ this._sink.set(dataID, sinkRecord);
1038
+ }
1039
+ return sinkRecord;
1040
+ };
1041
+ RelayRecordSourceMutator.prototype.create = function (dataID) {
1042
+ var record = RelayModernRecord.create(dataID);
1043
+ this._sink.set(dataID, record);
1044
+ };
1045
+ RelayRecordSourceMutator.prototype.delete = function (dataID) {
1046
+ this._sink.delete(dataID);
1047
+ };
1048
+ RelayRecordSourceMutator.prototype.getStatus = function (dataID) {
1049
+ return this._sink.has(dataID) ? this._sink.getStatus(dataID) : this._base.getStatus(dataID);
1050
+ };
1051
+ RelayRecordSourceMutator.prototype.setValue = function (dataID, storageKey, value) {
1052
+ var sinkRecord = this._getSinkRecord(dataID);
1053
+ RelayModernRecord.setValue(sinkRecord, storageKey, value);
1054
+ };
1055
+ RelayRecordSourceMutator.prototype.setLinkedRecordID = function (dataID, storageKey, linkedID) {
1056
+ var sinkRecord = this._getSinkRecord(dataID);
1057
+ RelayModernRecord.setLinkedRecordID(sinkRecord, storageKey, linkedID);
1058
+ };
1059
+ RelayRecordSourceMutator.prototype.getLinkedRecordIDs = function (dataID, storageKey) {
1060
+ for (var ii = 0; ii < this.__sources.length; ii++) {
1061
+ var record = this.__sources[ii].get(dataID);
1062
+ if (record) {
1063
+ var linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, storageKey);
1064
+ if (linkedIDs !== undefined) {
1065
+ return linkedIDs;
1066
+ }
1067
+ } else if (record === null) {
1068
+ return null;
1069
+ }
1070
+ }
1071
+ };
1072
+ RelayRecordSourceMutator.prototype.setLinkedRecordIDs = function (dataID, storageKey, linkedIDs) {
1073
+ var sinkRecord = this._getSinkRecord(dataID);
1074
+ RelayModernRecord.setLinkedRecordIDs(sinkRecord, storageKey, linkedIDs);
1075
+ };
1076
+ return RelayRecordSourceMutator;
1077
+ }();
1078
+
1079
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1080
+
1081
+ /**
1082
+ * @internal
1083
+ *
1084
+ * A helper class for manipulating a given record from a record source via an
1085
+ * imperative/OO-style API.
1086
+ */
1087
+ var RelayRecordProxy = /** @class */function () {
1088
+ function RelayRecordProxy(source, mutator, dataID) {
1089
+ this._dataID = dataID;
1090
+ this._mutator = mutator;
1091
+ this._source = source;
1092
+ }
1093
+ RelayRecordProxy.prototype.getDataID = function () {
1094
+ return this._dataID;
1095
+ };
1096
+ RelayRecordProxy.prototype.setValue = function (value, name) {
1097
+ this._mutator.setValue(this._dataID, name, value);
1098
+ return this;
1099
+ };
1100
+ RelayRecordProxy.prototype.setLinkedRecord = function (record, name) {
1101
+ var linkedID = record.getDataID();
1102
+ this._mutator.setLinkedRecordID(this._dataID, name, linkedID);
1103
+ return this;
1104
+ };
1105
+ RelayRecordProxy.prototype.getLinkedRecords = function (name) {
1106
+ var _this = this;
1107
+ var linkedIDs = this._mutator.getLinkedRecordIDs(this._dataID, name);
1108
+ if (linkedIDs == null) {
1109
+ return linkedIDs;
1110
+ }
1111
+ return linkedIDs.map(function (linkedID) {
1112
+ return linkedID != null ? _this._source.get(linkedID) : linkedID;
1113
+ });
1114
+ };
1115
+ RelayRecordProxy.prototype.setLinkedRecords = function (records, name) {
1116
+ var linkedIDs = records.map(function (record) {
1117
+ return record && record.getDataID();
1118
+ });
1119
+ this._mutator.setLinkedRecordIDs(this._dataID, name, linkedIDs);
1120
+ return this;
1121
+ };
1122
+ return RelayRecordProxy;
1123
+ }();
1124
+
1125
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1126
+ /**
1127
+ * @internal
1128
+ *
1129
+ * A helper for manipulating a `RecordSource` via an imperative/OO-style API.
1130
+ */
1131
+ var RelayRecordSourceProxy = /** @class */function () {
1132
+ function RelayRecordSourceProxy(mutator) {
1133
+ this.__mutator = mutator;
1134
+ this._proxies = {};
1135
+ }
1136
+ RelayRecordSourceProxy.prototype.create = function (dataID) {
1137
+ this.__mutator.create(dataID);
1138
+ delete this._proxies[dataID];
1139
+ return this.get(dataID);
1140
+ };
1141
+ RelayRecordSourceProxy.prototype.delete = function (dataID) {
1142
+ delete this._proxies[dataID];
1143
+ this.__mutator.delete(dataID);
1144
+ };
1145
+ RelayRecordSourceProxy.prototype.get = function (dataID) {
1146
+ if (!this._proxies.hasOwnProperty(dataID)) {
1147
+ var status_1 = this.__mutator.getStatus(dataID);
1148
+ if (status_1 === RelayRecordState.EXISTENT) {
1149
+ this._proxies[dataID] = new RelayRecordProxy(this, this.__mutator, dataID);
1150
+ } else {
1151
+ this._proxies[dataID] = status_1 === RelayRecordState.NONEXISTENT ? null : undefined;
1152
+ }
1153
+ }
1154
+ return this._proxies[dataID];
1155
+ };
1156
+ RelayRecordSourceProxy.prototype.getRoot = function () {
1157
+ var root = this.get(RelayStoreUtils.ROOT_ID);
1158
+ if (!root) {
1159
+ root = this.create(RelayStoreUtils.ROOT_ID);
1160
+ }
1161
+ return root;
1162
+ };
1163
+ return RelayRecordSourceProxy;
1164
+ }();
1165
+
1166
+ /**
1167
+ * Copyright (c) Facebook, Inc. and its affiliates.
1168
+ *
1169
+ * This source code is licensed under the MIT license found in the
1170
+ * LICENSE file in the root directory of this source tree.
1171
+ *
1172
+ * @flow strict-local
1173
+ * @format
1174
+ */
1175
+ function mark(recordSource, selector, references) {
1176
+ var dataID = selector.dataID,
1177
+ node = selector.node;
1178
+ var marker = new RelayReferenceMarker(recordSource, references);
1179
+ marker.mark(node, dataID);
1180
+ }
1181
+ /**
1182
+ * @private
1183
+ */
1184
+ var RelayReferenceMarker = /** @class */function () {
1185
+ function RelayReferenceMarker(recordSource, references) {
1186
+ this._recordSource = recordSource;
1187
+ this._references = references;
1188
+ }
1189
+ RelayReferenceMarker.prototype.mark = function (node, dataID) {
1190
+ this._traverse(node, dataID);
1191
+ };
1192
+ RelayReferenceMarker.prototype._traverse = function (node, dataID) {
1193
+ if (dataID != null) {
1194
+ this._references.add(dataID);
1195
+ var record = this._recordSource.get(dataID);
1196
+ record != null && this._traverseSelections(node.selections, record);
1197
+ }
1198
+ };
1199
+ RelayReferenceMarker.prototype._traverseSelections = function (selections, record) {
1200
+ var _this = this;
1201
+ selections.forEach(function (selection) {
1202
+ var name = selection.name;
1203
+ if (selection.kind == LINKED_FIELD) {
1204
+ if (selection.plural) {
1205
+ var linkedIDs = RelayModernRecord.getLinkedRecordIDs(record, name) || [];
1206
+ linkedIDs.forEach(function (linkedID) {
1207
+ _this._traverse(selection, linkedID);
1208
+ });
1209
+ } else {
1210
+ var linkedID = RelayModernRecord.getLinkedRecordID(record, name);
1211
+ _this._traverse(selection, linkedID);
1212
+ }
1213
+ }
1214
+ });
1215
+ };
1216
+ return RelayReferenceMarker;
1217
+ }();
1218
+
1219
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1220
+ var resolvedPromise = Promise.resolve();
1221
+ /**
1222
+ * An alternative to setImmediate based on Promise.
1223
+ */
1224
+ function resolveImmediate(callback) {
1225
+ resolvedPromise.then(callback).catch(throwNext);
1226
+ }
1227
+ function throwNext(error) {
1228
+ setTimeout(function () {
1229
+ throw error;
1230
+ }, 0);
1231
+ }
1232
+ var ROOT_ID = RelayStoreUtils.ROOT_ID;
1233
+ function createStore() {
1234
+ return new RelayModernStore(new RelayRecordSource());
1235
+ }
1236
+ /**
1237
+ * @public
1238
+ *
1239
+ * An implementation of the `Store` interface defined in `RelayStoreTypes`.
1240
+ *
1241
+ * Note that a Store takes ownership of all records provided to it: other
1242
+ * objects may continue to hold a reference to such records but may not mutate
1243
+ * them. The static Relay core is architected to avoid mutating records that may have been
1244
+ * passed to a store: operations that mutate records will either create fresh
1245
+ * records or clone existing records and modify the clones. Record immutability
1246
+ * is also enforced in development mode by freezing all records passed to a store.
1247
+ */
1248
+ var RelayModernStore = /** @class */function () {
1249
+ function RelayModernStore(source) {
1250
+ var _this = this;
1251
+ this._gcStep = function () {
1252
+ if (_this._gcRun) {
1253
+ if (_this._gcRun.next().done) {
1254
+ _this._gcRun = null;
1255
+ } else {
1256
+ resolveImmediate(_this._gcStep);
1257
+ }
1258
+ }
1259
+ };
1260
+ this._currentWriteEpoch = 0;
1261
+ this._gcRun = null;
1262
+ this._recordSource = source;
1263
+ this._roots = new Map();
1264
+ this._updatedRecordIDs = new Set();
1265
+ this._subs = new Set();
1266
+ initializeRecordSource(this._recordSource);
1267
+ }
1268
+ RelayModernStore.prototype.getSource = function () {
1269
+ return this._recordSource;
1270
+ };
1271
+ RelayModernStore.prototype.commitUpdate = function (updater) {
1272
+ var sink = new RelayRecordSource();
1273
+ var mutator = new RelayRecordSourceMutator(this.getSource(), sink);
1274
+ var recordSourceProxy = new RelayRecordSourceProxy(mutator);
1275
+ updater(recordSourceProxy);
1276
+ this.publish(sink);
1277
+ this.notify();
1278
+ };
1279
+ RelayModernStore.prototype.retain = function (operation) {
1280
+ var _this = this;
1281
+ var id = operation.identifier;
1282
+ var disposed = false;
1283
+ var dispose = function () {
1284
+ // Ensure each retain can only dispose once
1285
+ if (disposed) {
1286
+ return;
1287
+ }
1288
+ disposed = true;
1289
+ // For Flow: guard against the entry somehow not existing
1290
+ var rootEntry = _this._roots.get(id);
1291
+ if (rootEntry == null) {
1292
+ return;
1293
+ }
1294
+ // Decrement the ref count: if it becomes zero it is eligible
1295
+ // for release.
1296
+ rootEntry.refCount -= 1;
1297
+ if (rootEntry.refCount === 0) {
1298
+ _this._roots.delete(id);
1299
+ _this.scheduleGC();
1300
+ }
1301
+ };
1302
+ var rootEntry = this._roots.get(id);
1303
+ if (rootEntry != null) {
1304
+ // If we've previously retained this operation, increment the refCount
1305
+ rootEntry.refCount += 1;
1306
+ } else {
1307
+ // Otherwise create a new entry for the operation
1308
+ this._roots.set(id, {
1309
+ operation: operation,
1310
+ refCount: 1
1311
+ });
1312
+ }
1313
+ return {
1314
+ dispose: dispose
1315
+ };
1316
+ };
1317
+ RelayModernStore.prototype.lookup = function (selector) {
1318
+ var source = this.getSource();
1319
+ return relayRead(source, selector);
1320
+ };
1321
+ // This method will return a list of updated owners from the subscriptions
1322
+ RelayModernStore.prototype.notify = function () {
1323
+ var _this = this;
1324
+ this._currentWriteEpoch += 1;
1325
+ var updateIds = this._updatedRecordIDs;
1326
+ var hasUpdatedRecords = updateIds.size !== 0;
1327
+ var source = this.getSource();
1328
+ this._subs.forEach(function (subscription) {
1329
+ _this._updateSub(source, subscription, updateIds, hasUpdatedRecords);
1330
+ });
1331
+ this._updatedRecordIDs.clear();
1332
+ };
1333
+ RelayModernStore.prototype._updateSub = function (source, subscription, updatedRecordIDs, hasUpdatedRecords) {
1334
+ var callback = subscription.callback,
1335
+ snapshot = subscription.snapshot;
1336
+ var hasOverlappingUpdates = hasUpdatedRecords && hasOverlappingIDs(snapshot.seenRecords, updatedRecordIDs);
1337
+ if (hasOverlappingUpdates) {
1338
+ var nextSnapshot = relayRead(source, snapshot.selector);
1339
+ var nextData = recycleNodesInto(snapshot.data, nextSnapshot.data);
1340
+ nextSnapshot = {
1341
+ data: nextData,
1342
+ seenRecords: nextSnapshot.seenRecords,
1343
+ selector: nextSnapshot.selector
1344
+ };
1345
+ subscription.snapshot = nextSnapshot;
1346
+ if (nextSnapshot.data !== snapshot.data) {
1347
+ callback(nextSnapshot);
1348
+ }
1349
+ }
1350
+ };
1351
+ RelayModernStore.prototype.publish = function (source) {
1352
+ var target = this.getSource();
1353
+ updateTargetFromSource(target, source, this._updatedRecordIDs);
1354
+ };
1355
+ RelayModernStore.prototype.subscribe = function (snapshot, callback) {
1356
+ var _this = this;
1357
+ var subscription = {
1358
+ callback: callback,
1359
+ snapshot: snapshot
1360
+ };
1361
+ var dispose = function () {
1362
+ _this._subs.delete(subscription);
1363
+ };
1364
+ this._subs.add(subscription);
1365
+ return {
1366
+ dispose: dispose
1367
+ };
1368
+ };
1369
+ RelayModernStore.prototype.scheduleGC = function () {
1370
+ if (this._gcRun) {
1371
+ return;
1372
+ }
1373
+ this._gcRun = this._collect();
1374
+ resolveImmediate(this._gcStep);
1375
+ };
1376
+ RelayModernStore.prototype._collect = function () {
1377
+ var startEpoch, references, _i, _a, operation, storeIDs, ii, dataID;
1378
+ return __generator(this, function (_b) {
1379
+ switch (_b.label) {
1380
+ case 0:
1381
+ startEpoch = this._currentWriteEpoch;
1382
+ references = new Set();
1383
+ _i = 0, _a = this._roots.values();
1384
+ _b.label = 1;
1385
+ case 1:
1386
+ if (!(_i < _a.length)) return [3 /*break*/, 4];
1387
+ operation = _a[_i].operation;
1388
+ mark(this._recordSource, operation.fragment, references);
1389
+ // Yield for other work after each operation
1390
+ return [4 /*yield*/];
1391
+ case 2:
1392
+ // Yield for other work after each operation
1393
+ _b.sent();
1394
+ // If the store was updated, restart
1395
+ if (startEpoch !== this._currentWriteEpoch) {
1396
+ return [3 /*break*/, 0];
1397
+ }
1398
+ _b.label = 3;
1399
+ case 3:
1400
+ _i++;
1401
+ return [3 /*break*/, 1];
1402
+ case 4:
1403
+ // Sweep records without references
1404
+ if (references.size === 0) {
1405
+ // Short-circuit if *nothing* is referenced
1406
+ this._recordSource.clear();
1407
+ } else {
1408
+ storeIDs = this._recordSource.getRecordIDs();
1409
+ for (ii = 0; ii < storeIDs.length; ii++) {
1410
+ dataID = storeIDs[ii];
1411
+ if (!references.has(dataID)) {
1412
+ this._recordSource.remove(dataID);
1413
+ }
1414
+ }
1415
+ }
1416
+ return [2 /*return*/];
1417
+ case 5:
1418
+ return [2 /*return*/];
1419
+ }
1420
+ });
1421
+ };
1422
+
1423
+ return RelayModernStore;
1424
+ }();
1425
+ function initializeRecordSource(target) {
1426
+ if (!target.has(ROOT_ID)) {
1427
+ var rootRecord = RelayModernRecord.create(ROOT_ID);
1428
+ target.set(ROOT_ID, rootRecord);
1429
+ }
1430
+ }
1431
+ /**
1432
+ * Updates the target with information from source, also updating a mapping of
1433
+ * which records in the target were changed as a result.
1434
+ * Additionally, will mark records as invalidated at the current write epoch
1435
+ * given the set of record ids marked as stale in this update.
1436
+ */
1437
+ function updateTargetFromSource(target, source, updatedRecordIDs) {
1438
+ // Update the target based on the changes present in source
1439
+ var dataIDs = source.getRecordIDs();
1440
+ for (var ii = 0; ii < dataIDs.length; ii++) {
1441
+ var dataID = dataIDs[ii];
1442
+ var sourceRecord = source.get(dataID);
1443
+ var targetRecord = target.get(dataID);
1444
+ if (sourceRecord && targetRecord) {
1445
+ // ReactFlightClientResponses are lazy and only materialize when readRoot
1446
+ // is called when we read the field, so if the record is a Flight field
1447
+ // we always use the new record's data regardless of whether
1448
+ // it actually changed. Let React take care of reconciliation instead.
1449
+ var nextRecord = RelayModernRecord.update(targetRecord, sourceRecord);
1450
+ if (nextRecord !== targetRecord) {
1451
+ updatedRecordIDs.add(dataID);
1452
+ target.set(dataID, nextRecord);
1453
+ }
1454
+ } else if (sourceRecord === null) {
1455
+ target.delete(dataID);
1456
+ if (targetRecord !== null) {
1457
+ updatedRecordIDs.add(dataID);
1458
+ }
1459
+ } else if (sourceRecord) {
1460
+ target.set(dataID, sourceRecord);
1461
+ updatedRecordIDs.add(dataID);
1462
+ } // don't add explicit undefined
1463
+ }
1464
+ }
1465
+
1466
+ exports.RecordSource = RelayRecordSource;
1467
+ exports.Store = RelayModernStore;
1468
+ exports.StoreProvider = StoreProvider;
1469
+ exports.createStore = createStore;
1470
+ exports.useFormSetValue = useFormSetValue;
1471
+ exports.useFormState = useFormState;
1472
+ exports.useFormSubmit = useFormSubmit;
1473
+ exports.useFormValue = useFormValue;
1474
+
1475
+ Object.defineProperty(exports, '__esModule', { value: true });
1476
+
1477
+ }));
1478
+ //# sourceMappingURL=relay-forms-nodeps.js.map