gform-react 1.2.0 → 1.4.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.
@@ -0,0 +1,565 @@
1
+ import _extends from '@babel/runtime/helpers/esm/extends';
2
+ import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
3
+ import _objectWithoutProperties from '@babel/runtime/helpers/esm/objectWithoutProperties';
4
+ import React, { useMemo, useState, createContext, useContext, useRef, useEffect } from 'react';
5
+ import _defineProperty from '@babel/runtime/helpers/esm/defineProperty';
6
+
7
+ const isObject = o => o && typeof o === 'object' && !Array.isArray(o);
8
+ const defaultFieldProps = {
9
+ text: {
10
+ value: ''
11
+ },
12
+ checkbox: {
13
+ value: false
14
+ },
15
+ number: {
16
+ value: 0
17
+ }
18
+ };
19
+ const typeValueDict = {
20
+ checkbox: 'checked',
21
+ number: 'valueAsNumber'
22
+ };
23
+ const _buildFormInitialValues = (rows = []) => {
24
+ const fields = {};
25
+ if (!Array.isArray(rows)) rows = [rows];
26
+ rows.forEach(row => {
27
+ const inputConfigs = _findInputs(row);
28
+ inputConfigs.forEach(config => {
29
+ if (fields[config.formKey]) {
30
+ console.warn(`[Duplicate Keys] - field with key '${config.formKey}' has already been defined.`);
31
+ }
32
+ const {
33
+ required = false,
34
+ max,
35
+ maxLength,
36
+ min,
37
+ minLength,
38
+ step,
39
+ pattern,
40
+ type = 'text',
41
+ defaultValue,
42
+ value,
43
+ checked,
44
+ defaultChecked,
45
+ formKey,
46
+ debounce,
47
+ validatorKey
48
+ } = config;
49
+ const defaultProps = defaultFieldProps[type] || defaultFieldProps.text;
50
+ const inputValue = value || defaultValue || checked || defaultChecked || defaultProps.value;
51
+ fields[config.formKey] = {
52
+ formKey,
53
+ type,
54
+ required,
55
+ max,
56
+ maxLength,
57
+ min,
58
+ minLength,
59
+ step,
60
+ pattern,
61
+ value: inputValue,
62
+ validatorKey,
63
+ debounce,
64
+ dirty: false,
65
+ touched: false,
66
+ gid: Math.random().toString(36)
67
+ };
68
+ Object.keys(fields[config.formKey]).forEach(key => {
69
+ if (typeof fields[config.formKey][key] === 'undefined') delete fields[config.formKey][key];
70
+ });
71
+ });
72
+ });
73
+ return {
74
+ fields,
75
+ loading: false
76
+ };
77
+ };
78
+ const _findInputs = (root, total = []) => {
79
+ var _root$props, _root$props2;
80
+ if (!root) return total;
81
+ if (Array.isArray(root)) {
82
+ root.forEach(element => _findInputs(element, total));
83
+ return total;
84
+ }
85
+ if ((_root$props = root.props) !== null && _root$props !== void 0 && _root$props.formKey) {
86
+ total.push(root.props);
87
+ return total;
88
+ }
89
+ return _findInputs((_root$props2 = root.props) === null || _root$props2 === void 0 ? void 0 : _root$props2.children, total);
90
+ };
91
+ const _findValidityKey = validity => {
92
+ for (const key in validity) {
93
+ if (key !== 'valid' && validity[key]) {
94
+ return key;
95
+ }
96
+ }
97
+ };
98
+ const hasSubmitter = form => {
99
+ if (!form) return false;
100
+ for (const element of form) {
101
+ if (element.type === 'submit') return true;
102
+ }
103
+ return false;
104
+ };
105
+ const _checkIfFormIsValid = fields => {
106
+ for (const f in fields) {
107
+ if (fields[f].error) {
108
+ return false;
109
+ }
110
+ }
111
+ return true;
112
+ };
113
+ const _toRawData = (fields, options = {}) => {
114
+ const data = {};
115
+ const {
116
+ include,
117
+ exclude,
118
+ transform
119
+ } = options;
120
+ if (include) {
121
+ include.forEach(key => {
122
+ var _fields$key;
123
+ return data[key] = (_fields$key = fields[key]) === null || _fields$key === void 0 ? void 0 : _fields$key.value;
124
+ });
125
+ } else for (const f in fields) {
126
+ data[f] = fields[f].value;
127
+ }
128
+ exclude === null || exclude === void 0 ? void 0 : exclude.forEach(key => delete data[key]);
129
+ if (transform) {
130
+ for (const key in transform) {
131
+ var _fields$key2;
132
+ const set = transform[key];
133
+ data[key] = set((_fields$key2 = fields[key]) === null || _fields$key2 === void 0 ? void 0 : _fields$key2.value);
134
+ }
135
+ }
136
+ return data;
137
+ };
138
+ const _toFormData = (form, options) => {
139
+ if (!form) return new FormData();
140
+ if (options) {
141
+ const {
142
+ exclude,
143
+ include,
144
+ transform
145
+ } = options;
146
+ let formData;
147
+ if (include) {
148
+ formData = new FormData();
149
+ include.forEach(key => {
150
+ var _form;
151
+ return formData.set(key, (_form = form[key]) === null || _form === void 0 ? void 0 : _form.value);
152
+ });
153
+ } else {
154
+ formData = new FormData(form);
155
+ exclude === null || exclude === void 0 ? void 0 : exclude.forEach(key => formData.delete(key));
156
+ }
157
+ if (transform) {
158
+ for (const key in transform) {
159
+ var _form$key;
160
+ const set = transform[key];
161
+ formData.set(key, set((_form$key = form[key]) === null || _form$key === void 0 ? void 0 : _form$key.value));
162
+ }
163
+ }
164
+ return formData;
165
+ }
166
+ return new FormData(form);
167
+ };
168
+ function _toURLSearchParams(options) {
169
+ let data;
170
+ if (options) {
171
+ const {
172
+ exclude,
173
+ include,
174
+ transform
175
+ } = options;
176
+ if (include) {
177
+ data = {};
178
+ include.forEach(key => {
179
+ var _this$key;
180
+ return data[key] = (_this$key = this[key]) === null || _this$key === void 0 ? void 0 : _this$key.value;
181
+ });
182
+ } else {
183
+ data = this.toRawData();
184
+ exclude === null || exclude === void 0 ? void 0 : exclude.forEach(key => delete data[key]);
185
+ }
186
+ if (transform) {
187
+ for (const key in transform) {
188
+ var _this$key2;
189
+ const set = transform[key];
190
+ data[key] = set((_this$key2 = this[key]) === null || _this$key2 === void 0 ? void 0 : _this$key2.value);
191
+ }
192
+ }
193
+ } else data = this.toRawData();
194
+ return new URLSearchParams(data);
195
+ }
196
+ function __debounce(timeout, id) {
197
+ return new Promise(resolve => {
198
+ var _this$id;
199
+ if ((_this$id = this[id]) !== null && _this$id !== void 0 && _this$id.timerId) clearTimeout(this[id].timerId);
200
+ const timerId = setTimeout(() => resolve(), timeout);
201
+ if (this[id]) {
202
+ this[id].timerId = timerId;
203
+ } else this[id] = {
204
+ timerId
205
+ };
206
+ });
207
+ }
208
+ const _debounce = __debounce.bind({});
209
+ const _extractValue = (e, unknown) => {
210
+ if (e.target) {
211
+ if (Object.hasOwn(typeValueDict, e.target.type)) return e.target[typeValueDict[e.target.type]];
212
+ return e.target.value;
213
+ }
214
+ return e.value || (isObject(unknown) ? unknown.value : unknown);
215
+ };
216
+ const _checkResult = (handlerResult, value) => typeof handlerResult === 'boolean' ? handlerResult : typeof value === 'string' ? !handlerResult.test(value) : false;
217
+ const _merge = (target = {}, ...nodes) => {
218
+ if (!nodes.length) return target;
219
+ const next = nodes.shift();
220
+ if (isObject(next)) {
221
+ for (const key in next) {
222
+ target[key] = target[key] ? _objectSpread(_objectSpread({}, target[key]), next[key]) : next[key];
223
+ }
224
+ }
225
+ return _merge(target, ...nodes);
226
+ };
227
+
228
+ const useForm = (children, validators = {}, optimized = false) => {
229
+ const initialValues = useMemo(() => _buildFormInitialValues(typeof children === 'function' ? children({}) : children), [children]);
230
+ const [state, setState] = useState(initialValues);
231
+ const _validateInputHandler = (input, e) => {
232
+ if (!input) return;
233
+ const element = e.target;
234
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
235
+ if (!input.checkValidity) input.checkValidity = () => element.checkValidity();
236
+ element.setCustomValidity('');
237
+ const validityKey = _findValidityKey(element.validity);
238
+ _validateInput(input, validityKey, v => element.setCustomValidity(v));
239
+ if (!validityKey && input.error) {
240
+ element.setCustomValidity(input.errorText || 'error');
241
+ }
242
+ } else {
243
+ _validateInput(input, input.required && !input.value ? 'valueMissing' : undefined);
244
+ }
245
+ };
246
+ const _updateInputHandler = (key, e, unknown) => {
247
+ const value = _extractValue(e, unknown);
248
+ _updateInput(key, value);
249
+ _validateInputHandler(state.fields[key], e);
250
+ };
251
+ const _validateInput = (input, validityKey, setValidity) => {
252
+ const inputValidator = validators[input.validatorKey || input.formKey] || validators['*'];
253
+ inputValidator && __validateInput(input, inputValidator, validityKey, setValidity);
254
+ input.touched = true;
255
+ _dispatchChanges(input, input.formKey);
256
+ };
257
+ const _updateInput = (key, value) => {
258
+ const input = state.fields[key];
259
+ input.value = value;
260
+ input.dirty = true;
261
+ };
262
+ const _dispatchChanges = (changes, key) => setState(prev => {
263
+ if (key) {
264
+ return _objectSpread(_objectSpread({}, prev), {}, {
265
+ fields: _objectSpread(_objectSpread({}, prev.fields), {}, {
266
+ [key]: _objectSpread(_objectSpread({}, prev.fields[key]), changes)
267
+ })
268
+ });
269
+ }
270
+ return _objectSpread(_objectSpread({}, prev), changes);
271
+ });
272
+ const __validateInput = (input, inputValidator, validityKey, setValidity) => {
273
+ for (const index in inputValidator.constraintHandlers) {
274
+ const result = inputValidator.constraintHandlers[index](input, validityKey);
275
+ input.error = _checkResult(result, input.value);
276
+ if (input.error) return;
277
+ }
278
+ for (const index in inputValidator.handlers) {
279
+ const result = inputValidator.handlers[index](input, state.fields);
280
+ input.error = _checkResult(result, input.value);
281
+ if (input.error) return;
282
+ }
283
+ input.errorText = '';
284
+ if (inputValidator.asyncHandlers.length) {
285
+ input.error = true;
286
+ _debounce(input.debounce || 300, `${input.gid}-async`).then(() => {
287
+ const validateAsync = async () => {
288
+ for (const index in inputValidator.asyncHandlers) {
289
+ const result = await inputValidator.asyncHandlers[index](input, state.fields);
290
+ input.error = _checkResult(result, input.value);
291
+ if (input.error) break;
292
+ }
293
+ if (!input.error) input.errorText = '';
294
+ _dispatchChanges({
295
+ error: input.error,
296
+ errorText: input.errorText
297
+ }, input.formKey);
298
+ setValidity === null || setValidity === void 0 ? void 0 : setValidity(input.errorText);
299
+ };
300
+ validateAsync();
301
+ });
302
+ }
303
+ };
304
+ return {
305
+ state,
306
+ _updateInputHandler,
307
+ _validateInputHandler,
308
+ _dispatchChanges,
309
+ optimized
310
+ };
311
+ };
312
+
313
+ const gFormContext = createContext({
314
+ state: {
315
+ fields: {},
316
+ loading: false
317
+ },
318
+ _updateInputHandler: () => null,
319
+ _validateInputHandler: () => null,
320
+ _dispatchChanges: () => null,
321
+ optimized: false
322
+ });
323
+ const useGenericFormContext = () => useContext(gFormContext);
324
+ const GFormContextProvider = gFormContext.Provider;
325
+
326
+ const _excluded$1 = ["loader", "stateRef", "onSubmit", "onChange", "children", "validators", "onInit", "optimized"];
327
+ const GForm = _ref => {
328
+ let {
329
+ loader = React.createElement("div", null, "loading"),
330
+ stateRef,
331
+ onSubmit,
332
+ onChange,
333
+ children,
334
+ validators,
335
+ onInit,
336
+ optimized
337
+ } = _ref,
338
+ rest = _objectWithoutProperties(_ref, _excluded$1);
339
+ const formRef = useRef(null);
340
+ const values = useForm(children, validators, optimized);
341
+ const {
342
+ state,
343
+ _updateInputHandler,
344
+ _validateInputHandler,
345
+ _dispatchChanges
346
+ } = values;
347
+ const formState = useMemo(() => {
348
+ const _isFormValid = _checkIfFormIsValid(state.fields);
349
+ const formState = _objectSpread(_objectSpread({}, state.fields), {}, {
350
+ isValid: _isFormValid,
351
+ isInvalid: !_isFormValid,
352
+ loading: state.loading,
353
+ toRawData: options => _toRawData(state.fields, options),
354
+ toFormData: () => _toFormData(formRef.current),
355
+ toURLSearchParams: _toURLSearchParams,
356
+ checkValidity: function () {
357
+ var _formRef$current;
358
+ this.isValid = ((_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.checkValidity()) || false;
359
+ this.isInvalid = !this.isValid;
360
+ return this.isValid;
361
+ },
362
+ setLoading: p => _dispatchChanges({
363
+ loading: typeof p === 'function' ? p(state.loading) : p
364
+ })
365
+ });
366
+ if (stateRef) stateRef.current = formState;
367
+ return formState;
368
+ }, [state.fields]);
369
+ const form = useMemo(() => {
370
+ const formChildren = typeof children === 'function' ? children(formState) : children;
371
+ const _onSubmit = e => {
372
+ e.preventDefault();
373
+ onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(formState, e);
374
+ };
375
+ return optimized ? React.createElement("form", _extends({}, rest, {
376
+ ref: formRef,
377
+ onBlur: e => {
378
+ _validateInputHandler(state.fields[e.target.name], e);
379
+ },
380
+ onInvalid: e => {
381
+ e.preventDefault();
382
+ _validateInputHandler(state.fields[e.target.name], e);
383
+ },
384
+ onChange: (e, unknown) => {
385
+ _updateInputHandler(e.target.name, e, unknown);
386
+ onChange === null || onChange === void 0 ? void 0 : onChange(formState, e);
387
+ },
388
+ onSubmit: _onSubmit
389
+ }), formChildren) : React.createElement("form", _extends({}, rest, {
390
+ ref: formRef,
391
+ onSubmit: _onSubmit
392
+ }), formChildren);
393
+ }, [formState, children]);
394
+ useEffect(() => {
395
+ if (!hasSubmitter(formRef.current)) {
396
+ console.warn(`[No Submit Button] - you have created a form without a button type=submit, this will prevent the onSubmit event from being fired.\nif you have a button with onClick event that handle the submission of the form then ignore this warning\nbut don't forget to manually invoke the checkValidity() function and to check if the form is valid before perfoming any action, for example:\nif (formState.checkValidity()) { \n\t//do somthing\n}\n`);
397
+ }
398
+ const dispatchers = Object.keys(state.fields).reduce((fields, key) => {
399
+ fields[key] = {
400
+ dispatchChanges: changes => _dispatchChanges(changes, key)
401
+ };
402
+ return fields;
403
+ }, {});
404
+ if (onInit) {
405
+ const _handler = _c => {
406
+ _dispatchChanges({
407
+ fields: _merge({}, state.fields, dispatchers, _c)
408
+ });
409
+ };
410
+ const changes = onInit(formState);
411
+ changes instanceof Promise ? changes.then(_handler) : _handler(changes);
412
+ } else {
413
+ _dispatchChanges({
414
+ fields: _merge({}, state.fields, dispatchers)
415
+ });
416
+ }
417
+ }, []);
418
+ return React.createElement(GFormContextProvider, {
419
+ value: values
420
+ }, state.loading ? loader : form);
421
+ };
422
+
423
+ const _excluded = ["formKey", "element", "title", "type", "validatorKey", "fetch", "fetchDeps", "optimized", "defaultChecked", "defaultValue", "checked", "value", "debounce"];
424
+ const GInput = _ref => {
425
+ let {
426
+ formKey,
427
+ element,
428
+ title,
429
+ type,
430
+ validatorKey,
431
+ fetch,
432
+ fetchDeps = [],
433
+ optimized,
434
+ defaultChecked,
435
+ defaultValue,
436
+ checked,
437
+ value,
438
+ debounce = 300
439
+ } = _ref,
440
+ rest = _objectWithoutProperties(_ref, _excluded);
441
+ const {
442
+ state: {
443
+ fields
444
+ },
445
+ _updateInputHandler,
446
+ _validateInputHandler,
447
+ _dispatchChanges,
448
+ optimized: formOptimized
449
+ } = useGenericFormContext();
450
+ const inputState = fields[formKey];
451
+ const _element = useMemo(() => {
452
+ let value, checked;
453
+ if (type === 'checkbox') checked = inputState.value || false;else value = inputState.value || '';
454
+ const _props = _objectSpread(_objectSpread({}, rest), {}, {
455
+ type,
456
+ name: formKey,
457
+ value,
458
+ checked,
459
+ title: title || inputState.errorText
460
+ });
461
+ if (!formOptimized || !optimized) {
462
+ _props.onBlur = e => _validateInputHandler(inputState, e);
463
+ _props.onInvalid = e => {
464
+ e.preventDefault();
465
+ _validateInputHandler(inputState, e);
466
+ };
467
+ _props.onChange = (e, unknown) => _updateInputHandler(formKey, e, unknown);
468
+ }
469
+ if (element) {
470
+ return element(inputState, _props);
471
+ }
472
+ return React.createElement("input", _props);
473
+ }, [inputState, element]);
474
+ const _fetchDeps = useMemo(() => fetchDeps.map(key => fields[key].value), [fields]);
475
+ useEffect(() => {
476
+ if (fetch) {
477
+ _debounce(debounce, `${inputState.gid}-fetch`).then(() => {
478
+ const res = fetch(inputState, fields);
479
+ res instanceof Promise ? res.then(state => state && _dispatchChanges(state, formKey)) : res && _dispatchChanges(res, formKey);
480
+ });
481
+ }
482
+ }, _fetchDeps);
483
+ return _element;
484
+ };
485
+
486
+ class GValidator {
487
+ get handlers() {
488
+ return this._handlers;
489
+ }
490
+ get constraintHandlers() {
491
+ return this._constraintHandlers;
492
+ }
493
+ get asyncHandlers() {
494
+ return this._asyncHandlers;
495
+ }
496
+ constructor(baseValidator) {
497
+ _defineProperty(this, "_handlers", void 0);
498
+ _defineProperty(this, "_constraintHandlers", void 0);
499
+ _defineProperty(this, "_asyncHandlers", void 0);
500
+ _defineProperty(this, "_track", void 0);
501
+ const baseHandlers = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.handlers) || [];
502
+ const baseConstraintHandlers = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.constraintHandlers) || [];
503
+ const baseHandlersAsync = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.asyncHandlers) || [];
504
+ this._handlers = new Array().concat(baseHandlers);
505
+ this._constraintHandlers = new Array().concat(baseConstraintHandlers);
506
+ this._asyncHandlers = new Array().concat(baseHandlersAsync);
507
+ {
508
+ this._track = [];
509
+ }
510
+ }
511
+ withRequiredMessage(message) {
512
+ return this.__addConstraintValidationHandler('valueMissing', message);
513
+ }
514
+ withMaxLengthMessage(message) {
515
+ return this.__addConstraintValidationHandler('tooLong', message);
516
+ }
517
+ withMinLengthMessage(message) {
518
+ return this.__addConstraintValidationHandler('tooShort', message);
519
+ }
520
+ withPatternMismatchMessage(message) {
521
+ return this.__addConstraintValidationHandler('patternMismatch', message);
522
+ }
523
+ withBadInputMessage(message) {
524
+ return this.__addConstraintValidationHandler('badInput', message);
525
+ }
526
+ withRangeUnderflowMessage(message) {
527
+ return this.__addConstraintValidationHandler('rangeUnderflow', message);
528
+ }
529
+ withRangeOverflowMessage(message) {
530
+ return this.__addConstraintValidationHandler('rangeOverflow', message);
531
+ }
532
+ withTypeMismatchMessage(message) {
533
+ return this.__addConstraintValidationHandler('typeMismatch', message);
534
+ }
535
+ withStepMismatchMessage(message) {
536
+ return this.__addConstraintValidationHandler('stepMismatch', message);
537
+ }
538
+ withCustomValidation(handler) {
539
+ this._handlers.push(handler);
540
+ return this;
541
+ }
542
+ withCustomValidationAsync(handler) {
543
+ this._asyncHandlers.push(handler);
544
+ return this;
545
+ }
546
+ __addConstraintValidationHandler(validityKey, message) {
547
+ {
548
+ if (this._track.includes(validityKey)) {
549
+ console.warn(`[Duplicate Handlers] - handler for '${validityKey}' has already been defined`);
550
+ }
551
+ this._track.push(validityKey);
552
+ }
553
+ this._constraintHandlers.push((input, key) => {
554
+ if (key === validityKey) {
555
+ input.errorText = typeof message === 'string' ? message : message(input);
556
+ return true;
557
+ }
558
+ return false;
559
+ });
560
+ return this;
561
+ }
562
+ }
563
+
564
+ export { GForm, GInput, GValidator };
565
+ //# sourceMappingURL=index.development.js.map