UNPKG

22 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = void 0;
7
8var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
9
10var _react = _interopRequireDefault(require("react"));
11
12var _utilities = require("./utilities");
13
14var _components = require("./components");
15
16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
17
18function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
19
20function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
21
22function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
23
24function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
25
26function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
27
28function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
29
30function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
31
32function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
33
34function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
35
36function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
37
38function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
39
40function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
41
42function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
43
44function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
45
46function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
47
48function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
49
50function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
51
52function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
53
54function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
55
56function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
57
58function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
59
60function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
61
62var FormState = /*#__PURE__*/function (_React$PureComponent) {
63 _inherits(FormState, _React$PureComponent);
64
65 var _super = _createSuper(FormState);
66
67 function FormState() {
68 var _this;
69
70 _classCallCheck(this, FormState);
71
72 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
73 args[_key] = arguments[_key];
74 }
75
76 _this = _super.call.apply(_super, [this].concat(args));
77 _this.state = createFormState(_this.props.initialValues, _this.props.externalErrors);
78 _this.mounted = false;
79 _this.fieldsWithHandlers = new WeakMap();
80
81 _this.reset = function () {
82 return new Promise(function (resolve) {
83 _this.setState(function (_state, props) {
84 return createFormState(props.initialValues, props.externalErrors);
85 }, function () {
86 return resolve();
87 });
88 });
89 };
90
91 _this.submit = /*#__PURE__*/function () {
92 var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(event) {
93 var _this$props, onSubmit, validateOnSubmit, _assertThisInitialize, formData, clientErrors, errors;
94
95 return _regenerator["default"].wrap(function _callee$(_context) {
96 while (1) {
97 switch (_context.prev = _context.next) {
98 case 0:
99 _this$props = _this.props, onSubmit = _this$props.onSubmit, validateOnSubmit = _this$props.validateOnSubmit;
100 _assertThisInitialize = _assertThisInitialized(_this), formData = _assertThisInitialize.formData;
101
102 if (_this.mounted) {
103 _context.next = 4;
104 break;
105 }
106
107 return _context.abrupt("return");
108
109 case 4:
110 if (event && event.preventDefault && !event.defaultPrevented) {
111 event.preventDefault();
112 }
113
114 if (!(onSubmit == null)) {
115 _context.next = 7;
116 break;
117 }
118
119 return _context.abrupt("return");
120
121 case 7:
122 _this.setState({
123 submitting: true
124 });
125
126 if (!validateOnSubmit) {
127 _context.next = 15;
128 break;
129 }
130
131 _context.next = 11;
132 return _this.validateForm();
133
134 case 11:
135 clientErrors = _this.clientErrors;
136
137 if (!(clientErrors.length > 0)) {
138 _context.next = 15;
139 break;
140 }
141
142 _this.setState({
143 submitting: false,
144 errors: clientErrors
145 });
146
147 return _context.abrupt("return");
148
149 case 15:
150 _context.next = 17;
151 return onSubmit(formData);
152
153 case 17:
154 _context.t0 = _context.sent;
155
156 if (_context.t0) {
157 _context.next = 20;
158 break;
159 }
160
161 _context.t0 = [];
162
163 case 20:
164 errors = _context.t0;
165
166 if (_this.mounted) {
167 _context.next = 23;
168 break;
169 }
170
171 return _context.abrupt("return");
172
173 case 23:
174 if (errors.length > 0) {
175 _this.updateRemoteErrors(errors);
176
177 _this.setState({
178 submitting: false
179 });
180 } else {
181 _this.setState({
182 submitting: false,
183 errors: errors
184 });
185 }
186
187 case 24:
188 case "end":
189 return _context.stop();
190 }
191 }
192 }, _callee);
193 }));
194
195 return function (_x) {
196 return _ref.apply(this, arguments);
197 };
198 }();
199
200 _this.fieldWithHandlers = function (field, fieldPath) {
201 if (_this.fieldsWithHandlers.has(field)) {
202 return _this.fieldsWithHandlers.get(field);
203 }
204
205 var result = _objectSpread(_objectSpread({}, field), {}, {
206 name: String(fieldPath),
207 onChange: _this.updateField.bind(_assertThisInitialized(_this), fieldPath),
208 onBlur: _this.blurField.bind(_assertThisInitialized(_this), fieldPath)
209 });
210
211 _this.fieldsWithHandlers.set(field, result);
212
213 return result;
214 };
215
216 return _this;
217 }
218
219 _createClass(FormState, [{
220 key: "componentDidMount",
221 value: function componentDidMount() {
222 this.mounted = true;
223 }
224 }, {
225 key: "componentWillUnmount",
226 value: function componentWillUnmount() {
227 this.mounted = false;
228 }
229 }, {
230 key: "render",
231 value: function render() {
232 var children = this.props.children;
233 var submitting = this.state.submitting;
234 var submit = this.submit,
235 reset = this.reset,
236 formData = this.formData;
237 return children(_objectSpread(_objectSpread({}, formData), {}, {
238 submit: submit,
239 reset: reset,
240 submitting: submitting
241 }));
242 } // eslint-disable-next-line @shopify/react-prefer-private-members
243
244 }, {
245 key: "validateForm",
246 value: function validateForm() {
247 var _this2 = this;
248
249 return new Promise(function (resolve) {
250 _this2.setState(runAllValidators, function () {
251 return resolve();
252 });
253 });
254 } // eslint-disable-next-line @shopify/react-prefer-private-members
255
256 }, {
257 key: "updateField",
258 value: function updateField(fieldPath, value) {
259 var _this3 = this;
260
261 this.setState(function (_ref2) {
262 var fields = _ref2.fields,
263 dirtyFields = _ref2.dirtyFields;
264 var field = fields[fieldPath];
265 var newValue = typeof value === 'function' ? value(field.value) : value;
266 var dirty = !(0, _utilities.isEqual)(newValue, field.initialValue);
267
268 var updatedField = _this3.getUpdatedField({
269 fieldPath: fieldPath,
270 field: field,
271 value: newValue,
272 dirty: dirty
273 });
274
275 return {
276 dirtyFields: _this3.getUpdatedDirtyFields({
277 fieldPath: fieldPath,
278 dirty: dirty,
279 dirtyFields: dirtyFields
280 }),
281 fields: updatedField === field ? fields : _objectSpread(_objectSpread({}, fields), {}, _defineProperty({}, fieldPath, updatedField))
282 };
283 });
284 }
285 }, {
286 key: "getUpdatedDirtyFields",
287 value: function getUpdatedDirtyFields(_ref3) {
288 var fieldPath = _ref3.fieldPath,
289 dirty = _ref3.dirty,
290 dirtyFields = _ref3.dirtyFields;
291 var dirtyFieldsSet = new Set(dirtyFields);
292
293 if (dirty) {
294 dirtyFieldsSet.add(fieldPath);
295 } else {
296 dirtyFieldsSet["delete"](fieldPath);
297 }
298
299 var newDirtyFields = Array.from(dirtyFieldsSet);
300 return dirtyFields.length === newDirtyFields.length ? dirtyFields : newDirtyFields;
301 }
302 }, {
303 key: "getUpdatedField",
304 value: function getUpdatedField(_ref4) {
305 var fieldPath = _ref4.fieldPath,
306 field = _ref4.field,
307 value = _ref4.value,
308 dirty = _ref4.dirty;
309 // We only want to update errors as the user types if they already have an error.
310 // https://polaris.shopify.com/patterns/error-messages#section-form-validation
311 var skipValidation = field.error == null;
312 var error = skipValidation ? field.error : this.validateFieldValue(fieldPath, {
313 value: value,
314 dirty: dirty
315 });
316
317 if (value === field.value && error === field.error) {
318 return field;
319 }
320
321 return _objectSpread(_objectSpread({}, field), {}, {
322 value: value,
323 dirty: dirty,
324 error: error
325 });
326 }
327 }, {
328 key: "blurField",
329 value: function blurField(fieldPath) {
330 var fields = this.state.fields;
331 var field = fields[fieldPath];
332 var error = this.validateFieldValue(fieldPath, field);
333
334 if (error == null) {
335 return;
336 }
337
338 this.setState(function (state) {
339 return {
340 fields: _objectSpread(_objectSpread({}, state.fields), {}, _defineProperty({}, fieldPath, _objectSpread(_objectSpread({}, state.fields[fieldPath]), {}, {
341 error: error
342 })))
343 };
344 });
345 }
346 }, {
347 key: "validateFieldValue",
348 value: function validateFieldValue(fieldPath, _ref5) {
349 var value = _ref5.value,
350 dirty = _ref5.dirty;
351
352 if (!dirty) {
353 return;
354 }
355
356 var _this$props$validator = this.props.validators,
357 validators = _this$props$validator === void 0 ? {} : _this$props$validator;
358 var fields = this.state.fields;
359 return runValidator(validators[fieldPath], value, fields);
360 }
361 }, {
362 key: "updateRemoteErrors",
363 value: function updateRemoteErrors(errors) {
364 this.setState(function (_ref6) {
365 var fields = _ref6.fields,
366 externalErrors = _ref6.externalErrors;
367 return {
368 errors: errors,
369 fields: fieldsWithErrors(fields, [].concat(_toConsumableArray(errors), _toConsumableArray(externalErrors)))
370 };
371 });
372 }
373 }, {
374 key: "formData",
375 get: function get() {
376 var errors = this.state.errors;
377 var _this$props$externalE = this.props.externalErrors,
378 externalErrors = _this$props$externalE === void 0 ? [] : _this$props$externalE;
379 var fields = this.fields,
380 dirty = this.dirty,
381 valid = this.valid;
382 return {
383 dirty: dirty,
384 valid: valid,
385 errors: [].concat(_toConsumableArray(errors), _toConsumableArray(externalErrors)),
386 fields: fields
387 };
388 }
389 }, {
390 key: "dirty",
391 get: function get() {
392 return this.state.dirtyFields.length > 0;
393 }
394 }, {
395 key: "valid",
396 get: function get() {
397 var _this$state = this.state,
398 errors = _this$state.errors,
399 externalErrors = _this$state.externalErrors;
400 return !this.hasClientErrors && errors.length === 0 && externalErrors.length === 0;
401 }
402 }, {
403 key: "hasClientErrors",
404 get: function get() {
405 var fields = this.state.fields;
406 return Object.keys(fields).some(function (fieldPath) {
407 var field = fields[fieldPath];
408 return field.error != null;
409 });
410 }
411 }, {
412 key: "clientErrors",
413 get: function get() {
414 var fields = this.state.fields;
415 return (0, _utilities.flatMap)(Object.values(fields), function (_ref7) {
416 var error = _ref7.error;
417 return collectErrors(error);
418 });
419 }
420 }, {
421 key: "fields",
422 get: function get() {
423 var fields = this.state.fields;
424 var fieldDescriptors = (0, _utilities.mapObject)(fields, this.fieldWithHandlers);
425 return fieldDescriptors;
426 }
427 }], [{
428 key: "getDerivedStateFromProps",
429 value: function getDerivedStateFromProps(newProps, oldState) {
430 var initialValues = newProps.initialValues,
431 onInitialValuesChange = newProps.onInitialValuesChange,
432 _newProps$externalErr = newProps.externalErrors,
433 externalErrors = _newProps$externalErr === void 0 ? [] : _newProps$externalErr;
434 var externalErrorsChanged = !(0, _utilities.isEqual)(externalErrors, oldState.externalErrors);
435 var updatedExternalErrors = externalErrorsChanged ? {
436 externalErrors: externalErrors,
437 fields: fieldsWithErrors(oldState.fields, [].concat(_toConsumableArray(externalErrors), _toConsumableArray(oldState.errors)))
438 } : null;
439
440 switch (onInitialValuesChange) {
441 case 'ignore':
442 return updatedExternalErrors;
443
444 case 'reset-where-changed':
445 return reconcileFormState(initialValues, oldState, externalErrors);
446
447 case 'reset-all':
448 default:
449 var oldInitialValues = initialValuesFromFields(oldState.fields);
450 var valuesMatch = (0, _utilities.isEqual)(oldInitialValues, initialValues);
451
452 if (valuesMatch) {
453 return updatedExternalErrors;
454 }
455
456 return createFormState(initialValues, externalErrors);
457 }
458 }
459 }]);
460
461 return FormState;
462}(_react["default"].PureComponent);
463
464exports["default"] = FormState;
465FormState.List = _components.List;
466FormState.Nested = _components.Nested;
467
468function fieldsWithErrors(fields, errors) {
469 var errorDictionary = errors.reduce(function (accumulator, _ref8) {
470 var field = _ref8.field,
471 message = _ref8.message;
472
473 if (field == null) {
474 return accumulator;
475 }
476
477 return (0, _utilities.set)(accumulator, field, message);
478 }, {});
479 return (0, _utilities.mapObject)(fields, function (field, path) {
480 if (!errorDictionary[path]) {
481 return field;
482 }
483
484 return _objectSpread(_objectSpread({}, field), {}, {
485 error: errorDictionary[path]
486 });
487 });
488}
489
490function reconcileFormState(values, oldState) {
491 var externalErrors = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
492 var oldFields = oldState.fields;
493 var dirtyFields = new Set(oldState.dirtyFields);
494 var fields = (0, _utilities.mapObject)(values, function (value, key) {
495 var oldField = oldFields[key];
496
497 if ((0, _utilities.isEqual)(value, oldField.initialValue)) {
498 return oldField;
499 }
500
501 dirtyFields["delete"](key);
502 return {
503 value: value,
504 initialValue: value,
505 dirty: false
506 };
507 });
508 return _objectSpread(_objectSpread({}, oldState), {}, {
509 dirtyFields: Array.from(dirtyFields),
510 fields: fieldsWithErrors(fields, externalErrors)
511 });
512}
513
514function createFormState(values) {
515 var externalErrors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
516 var fields = (0, _utilities.mapObject)(values, function (value) {
517 return {
518 value: value,
519 initialValue: value,
520 dirty: false
521 };
522 });
523 return {
524 dirtyFields: [],
525 errors: [],
526 submitting: false,
527 externalErrors: externalErrors,
528 fields: fieldsWithErrors(fields, externalErrors)
529 };
530}
531
532function initialValuesFromFields(fields) {
533 return (0, _utilities.mapObject)(fields, function (_ref9) {
534 var initialValue = _ref9.initialValue;
535 return initialValue;
536 });
537}
538
539function runValidator() {
540 var validate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
541 var value = arguments.length > 1 ? arguments[1] : undefined;
542 var fields = arguments.length > 2 ? arguments[2] : undefined;
543
544 if (typeof validate === 'function') {
545 return validate(value, fields);
546 }
547
548 if (!Array.isArray(validate)) {
549 return;
550 }
551
552 var errors = validate.map(function (validator) {
553 return validator(value, fields);
554 }).filter(function (input) {
555 return input != null;
556 });
557
558 if (errors.length === 0) {
559 return;
560 }
561
562 return errors;
563}
564
565function runAllValidators(state, props) {
566 var fields = state.fields;
567 var validators = props.validators;
568
569 if (!validators) {
570 return null;
571 }
572
573 var updatedFields = (0, _utilities.mapObject)(fields, function (field, path) {
574 return _objectSpread(_objectSpread({}, field), {}, {
575 error: runValidator(validators[path], field.value, fields)
576 });
577 });
578 return _objectSpread(_objectSpread({}, state), {}, {
579 fields: updatedFields
580 });
581}
582
583function collectErrors(message) {
584 if (!message) {
585 return [];
586 }
587
588 if (typeof message === 'string') {
589 return [{
590 message: message
591 }];
592 }
593
594 if (Array.isArray(message)) {
595 return (0, _utilities.flatMap)(message, function (itemError) {
596 return collectErrors(itemError);
597 });
598 }
599
600 return (0, _utilities.flatMap)(Object.values(message), function (nestedError) {
601 return collectErrors(nestedError);
602 });
603}
\No newline at end of file