This repository has been archived by the owner on May 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Form.jsx
1271 lines (1070 loc) · 38.5 KB
/
Form.jsx
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
/*
Main form component.
This component expects:
### All Forms:
- collection
- currentUser
- client (Apollo client)
*/
import {
registerComponent,
Components,
runCallbacks,
getErrors,
getSetting,
Utils,
isIntlField,
mergeWithComponents,
formatLabel,
getIntlLabel,
getIntlKeys,
} from 'meteor/vulcan:core';
import React, { Component } from 'react';
import SimpleSchema from 'simpl-schema';
import PropTypes from 'prop-types';
import { intlShape } from 'meteor/vulcan:i18n';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import set from 'lodash/set';
import unset from 'lodash/unset';
import compact from 'lodash/compact';
import update from 'lodash/update';
import merge from 'lodash/merge';
import find from 'lodash/find';
import pick from 'lodash/pick';
import isEqual from 'lodash/isEqual';
import isEqualWith from 'lodash/isEqualWith';
import uniq from 'lodash/uniq';
import uniqBy from 'lodash/uniqBy';
import isObject from 'lodash/isObject';
import mapValues from 'lodash/mapValues';
import pickBy from 'lodash/pickBy';
import omit from 'lodash/omit';
import without from 'lodash/without';
import _filter from 'lodash/filter';
import omitBy from 'lodash/omitBy';
import { convertSchema, formProperties } from '../modules/schema_utils';
import { isEmptyValue } from '../modules/utils';
import { getParentPath } from '../modules/path_utils';
import { getEditableFields, getInsertableFields } from '../modules/schema_utils.js';
import withCollectionProps from './withCollectionProps';
import { callbackProps } from './propTypes';
// props that should trigger a form reset
const RESET_PROPS = [
'collection',
'collectionName',
'typeName',
'document',
'schema',
'currentUser',
'fields',
'removeFields',
'prefilledProps', // TODO: prefilledProps should be merged instead?
];
const compactParent = (object, path) => {
const parentPath = getParentPath(path);
// note: we only want to compact arrays, not objects
const compactIfArray = x => (Array.isArray(x) ? compact(x) : x);
update(object, parentPath, compactIfArray);
};
const getDefaultValues = convertedSchema => {
// TODO: make this work with nested schemas, too
return pickBy(mapValues(convertedSchema, field => field.defaultValue), value => value);
};
const compactObject = o => omitBy(o, f => f === null || f === undefined);
const getInitialStateFromProps = nextProps => {
const collection = nextProps.collection;
const schema = nextProps.schema ? new SimpleSchema(nextProps.schema) : collection.simpleSchema();
const convertedSchema = convertSchema(schema);
const formType = nextProps.document ? 'edit' : 'new';
// for new document forms, add default values to initial document
const defaultValues = formType === 'new' ? getDefaultValues(convertedSchema) : {};
// note: we remove null/undefined values from the loaded document so they don't overwrite possible prefilledProps
const initialDocument = merge({}, defaultValues, nextProps.prefilledProps, compactObject(nextProps.document));
//if minCount is specified, go ahead and create empty nested documents
Object.keys(convertedSchema).forEach(key => {
let minCount = convertedSchema[key].minCount;
if (minCount) {
initialDocument[key] = initialDocument[key] || [];
while (initialDocument[key].length < minCount) initialDocument[key].push({});
}
});
// remove all instances of the `__typename` property from document
Utils.removeProperty(initialDocument, '__typename');
return {
disabled: nextProps.disabled,
errors: [],
deletedValues: [],
currentValues: {},
originalSchema: convertSchema(schema, { removeArrays: false }),
// convert SimpleSchema schema into JSON object
schema: convertedSchema,
// Also store all field schemas (including nested schemas) in a flat structure
flatSchema: convertSchema(schema, { flatten: true }),
// the initial document passed as props
initialDocument,
// initialize the current document to be the same as the initial document
currentDocument: initialDocument,
};
};
/*
1. Constructor
2. Helpers
3. Errors
4. Context
4. Method & Callback
5. Render
*/
class SmartForm extends Component {
constructor(props) {
super(props);
const state = getInitialStateFromProps(props);
this.state = {
...state,
};
if(props.initCallback) props.initCallback(state.currentDocument);
}
defaultValues = {};
submitFormCallbacks = [];
successFormCallbacks = [];
failureFormCallbacks = [];
// --------------------------------------------------------------------- //
// ------------------------------- Helpers ----------------------------- //
// --------------------------------------------------------------------- //
/*
If a document is being passed, this is an edit form
*/
getFormType = () => {
return this.props.document ? 'edit' : 'new';
};
/*
Get a list of all insertable fields
*/
getInsertableFields = schema => {
return getInsertableFields(schema || this.state.schema, this.props.currentUser);
};
/*
Get a list of all editable fields
*/
getEditableFields = schema => {
return getEditableFields(schema || this.state.schema, this.props.currentUser, this.state.initialDocument);
};
/*
Get a list of all mutable (insertable/editable depending on current form type) fields
*/
getMutableFields = schema => {
return this.getFormType() === 'edit' ? this.getEditableFields(schema) : this.getInsertableFields(schema);
};
/*
Get the current document
*/
getDocument = () => {
return this.state.currentDocument;
};
/*
Like getDocument, but cross-reference with getFieldNames()
to only return fields that actually need to be submitted
Also remove any deleted values.
*/
getData = customArgs => {
// we want to keep prefilled data even for hidden/removed fields
let data = this.props.prefilledProps || {};
// omit prefilled props for nested fields
data = omitBy(data, (value, key) => key.endsWith('.$'));
const args = {
excludeRemovedFields: false,
excludeHiddenFields: false,
replaceIntlFields: true,
addExtraFields: false,
...customArgs,
};
// only keep relevant fields
// for intl fields, make sure we look in foo_intl and not foo
const fields = this.getFieldNames(args);
data = { ...data, ...pick(this.getDocument(), ...fields) };
// compact deleted values
this.state.deletedValues.forEach(path => {
if (path.includes('.')) {
/*
If deleted field is a nested field, nested array, or nested array item, try to compact its parent array
- Nested field: 'address.city'
- Nested array: 'addresses.1'
- Nested array item: 'addresses.1.city'
*/
compactParent(data, path);
}
});
// run data object through submitForm callbacks
data = runCallbacks({
callbacks: this.submitFormCallbacks,
iterator: data,
properties: { form: this },
});
return data;
};
/*
Get form components, in case any has been overwritten for this specific form
*/
getMergedComponents = () => mergeWithComponents(this.props.components || this.props.formComponents);
// --------------------------------------------------------------------- //
// -------------------------------- Fields ----------------------------- //
// --------------------------------------------------------------------- //
/*
Get all field groups
*/
getFieldGroups = () => {
// build fields array by iterating over the list of field names
let fields = this.getFieldNames().map(fieldName => {
// get schema for the current field
return this.createField(fieldName, this.state.schema);
});
fields = _.sortBy(fields, 'order');
// get list of all unique groups (based on their name) used in current fields
let groups = _.compact(uniqBy(_.pluck(fields, 'group'), g => g && g.name));
// for each group, add relevant fields
groups = groups.map(group => {
group.label = group.label || this.context.intl.formatMessage({ id: group.name }) || Utils.capitalize(group.name);
group.fields = _.filter(fields, field => {
return field.group && field.group.name === group.name;
});
return group;
});
// add default group if necessary
const defaultGroupFields = _filter(fields, field => !field.group);
if (defaultGroupFields.length) {
groups = [
{
name: 'default',
label: 'default',
order: 0,
fields: defaultGroupFields,
},
].concat(groups);
}
// sort by order
groups = _.sortBy(groups, 'order');
// console.log(groups);
return groups;
};
/*
Get a list of the fields to be included in the current form
Note: when submitting the form (getData()), do not include any extra fields.
*/
getFieldNames = args => {
// we do this to avoid having default values in arrow functions, which breaks MS Edge support. See https://github.com/meteor/meteor/issues/10171
let args0 = args || {};
const {
schema = this.state.schema,
excludeHiddenFields = true,
excludeRemovedFields = true,
replaceIntlFields = false,
addExtraFields = true,
} = args0;
const { fields, addFields } = this.props;
// get all editable/insertable fields (depending on current form type)
let relevantFields = this.getMutableFields(schema);
// if "fields" prop is specified, restrict list of fields to it
if (typeof fields !== 'undefined' && fields.length > 0) {
relevantFields = _.intersection(relevantFields, fields);
}
// if "hideFields" prop is specified, remove its fields
if (excludeRemovedFields) {
// OpenCRUD backwards compatibility
const removeFields = this.props.removeFields || this.props.hideFields;
if (typeof removeFields !== 'undefined' && removeFields.length > 0) {
relevantFields = _.difference(relevantFields, removeFields);
}
}
// if "addFields" prop is specified, add its fields
if (addExtraFields && typeof addFields !== 'undefined' && addFields.length > 0) {
relevantFields = relevantFields.concat(addFields);
}
// remove all hidden fields
if (excludeHiddenFields) {
const document = this.getDocument();
relevantFields = _.reject(relevantFields, fieldName => {
const hidden = schema[fieldName].hidden;
return typeof hidden === 'function' ? hidden({ ...this.props, document }) : hidden;
});
}
// replace intl fields
if (replaceIntlFields) {
relevantFields = relevantFields.map(fieldName => (isIntlField(schema[fieldName]) ? `${fieldName}_intl` : fieldName));
}
// remove any duplicates
relevantFields = uniq(relevantFields);
return relevantFields;
};
initField = (fieldName, fieldSchema) => {
const isArray = get(fieldSchema, 'type.0.type') === Array;
// intialize properties
let field = {
..._.pick(fieldSchema, formProperties),
document: this.state.initialDocument,
name: fieldName,
datatype: fieldSchema.type,
layout: this.props.layout,
input: fieldSchema.input || fieldSchema.control,
};
// if this is an array field also store its array item type
if (isArray) {
const itemFieldSchema = this.state.originalSchema[`${fieldName}.$`];
field.itemDatatype = get(itemFieldSchema, 'type.0.type');
}
field.label = this.getLabel(fieldName);
field.intlKeys = this.getIntlKeys(fieldName);
// // replace value by prefilled value if value is empty
// const prefill = fieldSchema.prefill || (fieldSchema.form && fieldSchema.form.prefill);
// if (prefill) {
// const prefilledValue = typeof prefill === 'function' ? prefill.call(fieldSchema) : prefill;
// if (!!prefilledValue && !field.value) {
// field.prefilledValue = prefilledValue;
// field.value = prefilledValue;
// }
// }
const document = this.getDocument();
// internationalize field options labels
if (field.options && Array.isArray(field.options)) {
field.options = field.options.map(option => ({ ...option, label: this.getOptionLabel(fieldName, option) }));
}
// if this an intl'd field, use a special intlInput
if (isIntlField(fieldSchema)) {
field.intlInput = true;
}
// add any properties specified in fieldSchema.form as extra props passed on
// to the form component, calling them if they are functions
const inputProperties = fieldSchema.form || fieldSchema.inputProperties || {};
for (const prop in inputProperties) {
const property = inputProperties[prop];
field[prop] =
typeof property === 'function' ?
property.call(fieldSchema, { ...this.props, fieldName, document, intl: this.context.intl }) :
property;
}
// add description as help prop
const description = this.getDescription(fieldName);
if (description) {
field.help = description;
}
return field;
};
handleFieldPath = (field, fieldName, parentPath) => {
const fieldPath = parentPath ? `${parentPath}.${fieldName}` : fieldName;
field.path = fieldPath;
if (field.defaultValue) {
set(this.defaultValues, fieldPath, field.defaultValue);
}
return field;
};
handleFieldParent = (field, parentFieldName) => {
// if field has a parent field, pass it on
if (parentFieldName) {
field.parentFieldName = parentFieldName;
}
return field;
};
handlePermissions = (field, fieldName, schema) => {
// if field is not creatable/updatable, disable it
if (!this.getMutableFields(schema).includes(fieldName)) {
field.disabled = true;
}
return field;
};
handleFieldChildren = (field, fieldName, fieldSchema, schema) => {
// array field
if (fieldSchema.arrayFieldSchema) {
field.arrayFieldSchema = fieldSchema.arrayFieldSchema;
// create a field that can be exploited by the form
field.arrayField = this.createArraySubField(fieldName, field.arrayFieldSchema, schema);
//field.nestedInput = true
}
// nested fields: set input to "nested"
if (fieldSchema.schema) {
field.nestedSchema = fieldSchema.schema;
field.nestedInput = true;
// get nested schema
// for each nested field, get field object by calling createField recursively
field.nestedFields = this.getFieldNames({
schema: field.nestedSchema,
addExtraFields: false,
}).map(subFieldName => {
return this.createField(subFieldName, field.nestedSchema, fieldName, field.path);
});
}
return field;
};
/*
Given a field's name, the containing schema, and parent, create the
complete field object to be passed to the component
*/
createField = (fieldName, schema, parentFieldName, parentPath) => {
const fieldSchema = schema[fieldName];
let field = this.initField(fieldName, fieldSchema);
field = this.handleFieldPath(field, fieldName, parentPath);
field = this.handleFieldParent(field, parentFieldName);
field = this.handlePermissions(field, fieldName, schema);
field = this.handleFieldChildren(field, fieldName, fieldSchema, schema);
return field;
};
createArraySubField = (fieldName, subFieldSchema, schema) => {
const subFieldName = `${fieldName}.$`;
let subField = this.initField(subFieldName, subFieldSchema);
// array subfield has the same path and permissions as its parent
// so we use parent name (fieldName) and not subfieldName
subField = this.handleFieldPath(subField, fieldName);
subField = this.handlePermissions(subField, fieldName, schema);
// we do not allow nesting yet
//subField = this.handleFieldChildren(field, fieldSchema)
return subField;
};
/*
Get a field's intl keys (useful for debugging)
*/
getIntlKeys = fieldName => {
const collectionName = this.props.collectionName.toLowerCase();
return getIntlKeys({
fieldName: fieldName,
collectionName,
schema: this.state.flatSchema,
});
};
/*
Get a field's label
*/
getLabel = (fieldName, fieldLocale) => {
const collectionName = this.props.collectionName.toLowerCase();
const label = formatLabel({
intl: this.context.intl,
fieldName: fieldName,
collectionName: collectionName,
schema: this.state.flatSchema,
});
if (fieldLocale) {
const intlFieldLocale = this.context.intl.formatMessage({
id: `locales.${fieldLocale}`,
defaultMessage: fieldLocale,
});
return `${label} (${intlFieldLocale})`;
} else {
return label;
}
};
/*
Get a field's description
(Same as getLabel but pass isDescription: true )
*/
getDescription = (fieldName) => {
const collectionName = this.props.collectionName.toLowerCase();
const description = getIntlLabel({
intl: this.context.intl,
fieldName: fieldName,
collectionName: collectionName,
schema: this.state.flatSchema,
isDescription: true,
});
return description || null;
}
/*
Get a field option's label
*/
getOptionLabel = (fieldName, option) => {
const collectionName = this.props.collectionName.toLowerCase();
const intlId = option.intlId || `${collectionName}.${fieldName}.${option.value}`;
return this.context.intl.formatMessage({
id: intlId,
defaultMessage: option.label,
});
};
// --------------------------------------------------------------------- //
// ------------------------------- Errors ------------------------------ //
// --------------------------------------------------------------------- //
/*
Add error to form state
Errors can have the following properties:
- id: used as an internationalization key, for example `errors.required`
- path: for field-specific errors, the path of the field with the issue
- properties: additional data. Will be passed to vulcan-i18n as values
- message: if id cannot be used as i81n key, message will be used
*/
throwError = error => {
let formErrors = getErrors(error);
// eslint-disable-next-line no-console
console.log(formErrors);
// add error(s) to state
this.setState(prevState => ({
errors: [...prevState.errors, ...formErrors],
}));
};
/*
Clear errors for a field
*/
clearFieldErrors = path => {
this.setState((prevState) => ({
errors: prevState.errors.filter(error => error.path !== path)
}));
};
// --------------------------------------------------------------------- //
// ------------------------------- Context ----------------------------- //
// --------------------------------------------------------------------- //
// add something to deleted values
addToDeletedValues = name => {
this.setState(prevState => ({
deletedValues: [...prevState.deletedValues, name],
}));
};
// add a callback to the form submission
addToSubmitForm = callback => {
this.submitFormCallbacks.push(callback);
};
// add a callback to form submission success
addToSuccessForm = callback => {
this.successFormCallbacks.push(callback);
};
// add a callback to form submission failure
addToFailureForm = callback => {
this.failureFormCallbacks.push(callback);
};
clearFormCallbacks = () => {
this.submitFormCallbacks = [];
this.successFormCallbacks = [];
this.failureFormCallbacks = [];
};
setFormState = fn => {
this.setState(fn);
};
submitFormContext = newValues => {
// keep the previous ones and extend (with possible replacement) with new ones
this.setState(
prevState => ({
currentValues: {
...prevState.currentValues,
...newValues,
}, // Submit form after setState update completed
}),
() => this.submitForm()
);
};
// pass on context to all child components
getChildContext = () => {
return {
throwError: this.throwError,
clearForm: this.clearForm,
refetchForm: this.refetchForm,
isChanged: this.isChanged,
submitForm: this.submitFormContext, //Change in name because we already have a function
// called submitForm, but no reason for the user to know
// about that
addToDeletedValues: this.addToDeletedValues,
updateCurrentValues: this.updateCurrentValues,
getDocument: this.getDocument,
getLabel: this.getLabel,
initialDocument: this.state.initialDocument,
setFormState: this.setFormState,
addToSubmitForm: this.addToSubmitForm,
addToSuccessForm: this.addToSuccessForm,
addToFailureForm: this.addToFailureForm,
clearFormCallbacks: this.clearFormCallbacks,
errors: this.state.errors,
currentValues: this.state.currentValues,
deletedValues: this.state.deletedValues,
};
};
// --------------------------------------------------------------------- //
// ------------------------------ Lifecycle ---------------------------- //
// --------------------------------------------------------------------- //
/*
When props change, reinitialize the form state
Triggered only for data related props (collection, document, currentUser etc.)
@see https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
*/
UNSAFE_componentWillReceiveProps(nextProps) {
const needReset = !!RESET_PROPS.find(prop => !isEqual(this.props[prop], nextProps[prop]));
if (needReset) {
const newState = getInitialStateFromProps(nextProps);
this.setState(newState);
if (nextProps.initCallback) nextProps.initCallback(newState.currentDocument);
}
}
/*
Manually update the current values of one or more fields(i.e. on change or blur).
*/
updateCurrentValues = (newValues, options = {}) => {
// default to overwriting old value with new
const { mode = 'overwrite' } = options;
const { changeCallback } = this.props;
// keep the previous ones and extend (with possible replacement) with new ones
this.setState(prevState => {
// keep only the relevant properties
const newState = {
currentValues: cloneDeep(prevState.currentValues),
currentDocument: cloneDeep(prevState.currentDocument),
deletedValues: cloneDeep(prevState.deletedValues),
};
Object.keys(newValues).forEach(key => {
const path = key;
let value = newValues[key];
if (isEmptyValue(value)) {
// delete value
unset(newState.currentValues, path);
set(newState.currentDocument, path, null);
newState.deletedValues = [...newState.deletedValues, path];
} else {
// 1. update currentValues
set(newState.currentValues, path, value);
// 2. update currentDocument
// For arrays and objects, give option to merge instead of overwrite
if (mode === 'merge' && (Array.isArray(value) || isObject(value))) {
const oldValue = get(newState.currentDocument, path);
set(newState.currentDocument, path, merge(oldValue, value));
} else {
set(newState.currentDocument, path, value);
}
// 3. in case value had previously been deleted, "undelete" it
newState.deletedValues = without(newState.deletedValues, path);
}
});
if (changeCallback) changeCallback(newState.currentDocument);
return newState;
});
};
/*
Install a route leave hook to warn the user if there are unsaved changes
*/
componentDidMount = () => {
this.checkRouteChange();
this.checkBrowserClosing();
};
/*
Remove the closing browser check on component unmount
see https://gist.github.com/mknabe/bfcb6db12ef52323954a28655801792d
*/
componentWillUnmount = () => {
if (this.getWarnUnsavedChanges()) {
// unblock route change
if (this.unblock) {
this.unblock();
}
// unblock browser change
window.onbeforeunload = undefined; //undefined instead of null to support IE
}
};
// -------------------- Check on form leaving ----- //
/**
* Check if we must warn user on unsaved change
*/
getWarnUnsavedChanges = () => {
let warnUnsavedChanges = getSetting('forms.warnUnsavedChanges');
if (typeof this.props.warnUnsavedChanges === 'boolean') {
warnUnsavedChanges = this.props.warnUnsavedChanges;
}
return warnUnsavedChanges;
};
// check for route change, prevent form content loss
checkRouteChange = () => {
// @see https://github.com/ReactTraining/react-router/issues/4635#issuecomment-297828995
// @see https://github.com/ReactTraining/history#blocking-transitions
if (this.getWarnUnsavedChanges()) {
this.unblock = this.props.history.block((location, action) => {
// return the message that will pop into a window.confirm alert
// if returns nothing, the message won't appear and the user won't be blocked
return this.handleRouteLeave();
/*
// React-router 3 implementtion
const routes = this.props.router.routes;
const currentRoute = routes[routes.length - 1];
this.props.router.setRouteLeaveHook(currentRoute, this.handleRouteLeave);
*/
});
}
};
// check for browser closing
checkBrowserClosing = () => {
//check for closing the browser with unsaved changes too
window.onbeforeunload = this.handlePageLeave;
};
/*
Check if the user has unsaved changes, returns a message if yes
and nothing if not
*/
handleRouteLeave = () => {
if (this.isChanged()) {
const message = this.context.intl.formatMessage({
id: 'forms.confirm_discard',
defaultMessage: 'Are you sure you want to discard your changes?',
});
return message;
}
};
/**
* Same for browser closing
*
* see https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
* the message returned is actually ignored by most browsers and a default message 'Are you sure you want to leave this page? You might have unsaved changes' is displayed. See the Notes section on the mozilla docs above
*/
handlePageLeave = event => {
if (this.isChanged()) {
const message = this.context.intl.formatMessage({
id: 'forms.confirm_discard',
defaultMessage: 'Are you sure you want to discard your changes?',
});
if (event) {
event.returnValue = message;
}
return message;
}
};
/*
Returns true if there are any differences between the initial document and the current one
*/
isChanged = () => {
const initialDocument = this.state.initialDocument;
const changedDocument = this.getDocument();
const changedValue = find(changedDocument, (value, key, collection) => {
return !isEqualWith(value, initialDocument[key], (objValue, othValue) => {
if (!objValue && !othValue) return true;
});
});
return typeof changedValue !== 'undefined';
};
/*
Refetch the document from the database (in case it was updated by another process or to reset the form)
*/
refetchForm = () => {
if (this.props.refetch) {
this.props.refetch();
}
};
/**
* Clears form errors and values.
*
* @example Clear form
* // form will be fully emptied, with exception of prefilled values
* clearForm({ document: {} });
*
* @example Reset/revert form
* // form will be reverted to its initial state
* clearForm();
*
* @example Clear with new values
* // form will be cleared but initialized with the new document
* const document = {
* // ... some values
* };
* clearForm({ document });
*
* @param {Object=} options
* @param {Object=} options.document
* Document to use as new initial document when values are cleared instead of
* the existing one. Note that prefilled props will be merged
*/
clearForm = ({ document } = {}) => {
document = document ? merge({}, this.props.prefilledProps, document) : null;
this.setState(prevState => ({
errors: [],
currentValues: {},
deletedValues: [],
currentDocument: document || prevState.initialDocument,
initialDocument: document || prevState.initialDocument,
disabled: false,
}));
};
newMutationSuccessCallback = result => {
this.mutationSuccessCallback(result, 'new');
};
editMutationSuccessCallback = result => {
this.mutationSuccessCallback(result, 'edit');
};
mutationSuccessCallback = (result, mutationType) => {
this.setState(prevState => ({ disabled: false, success: true }));
let document = result.data[Object.keys(result.data)[0]].data; // document is always on first property
// for new mutation, run refetch function if it exists
if (mutationType === 'new' && this.props.refetch) this.props.refetch();
// call the clear form method (i.e. trigger setState) only if the form has not been unmounted
// (we are in an async callback, everything can happen!)
if (this.form) {
this.clearForm({
document: mutationType === 'edit' ? document : undefined,
});
}
// run document through mutation success callbacks
document = runCallbacks({
callbacks: this.successFormCallbacks,
iterator: document,
properties: { form: this },
});
// run success callback if it exists
if (this.props.successCallback) this.props.successCallback(document, { form: this });
};
// catch graphql errors
mutationErrorCallback = (document, error) => {
this.setState(prevState => ({ disabled: false }));
// eslint-disable-next-line no-console
console.log('// graphQL Error');
// eslint-disable-next-line no-console
console.log(error);
// run mutation failure callbacks on error, we do not allow the callbacks to change the error
runCallbacks({
callbacks: this.failureFormCallbacks,
iterator: error,
properties: { error, form: this },
});
if (!_.isEmpty(error)) {
// add error to state
this.throwError(error);
}
// run error callback if it exists
if (this.props.errorCallback) this.props.errorCallback(document, error, { form: this });
// scroll back up to show error messages
Utils.scrollIntoView('.flash-message');
};
/*
Submit form handler
*/
submitForm = async event => {
event && event.preventDefault();
event && event.stopPropagation();
const { contextName } = this.props;
// if form is disabled (there is already a submit handler running) don't do anything
if (this.state.disabled) {
return;
}