gform-react 2.5.4 → 2.6.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 (55) hide show
  1. package/dist/cjs/gform-react.development.js +93 -78
  2. package/dist/cjs/gform-react.development.js.map +1 -1
  3. package/dist/cjs/gform-react.production.js +1 -1
  4. package/dist/cjs/gform-react.production.js.map +1 -1
  5. package/dist/cjs/index.js +8 -7
  6. package/dist/esm/GForm.development.js +160 -0
  7. package/dist/esm/GForm.development.js.map +1 -0
  8. package/dist/esm/GForm.production.js +1 -1
  9. package/dist/esm/GForm.production.js.map +1 -1
  10. package/dist/esm/GInput.development.js +105 -0
  11. package/dist/esm/GInput.development.js.map +1 -0
  12. package/dist/esm/GInput.production.js +1 -1
  13. package/dist/esm/GInput.production.js.map +1 -1
  14. package/dist/esm/GValidator.development.js +118 -0
  15. package/dist/esm/GValidator.development.js.map +1 -0
  16. package/dist/esm/GValidator.production.js +1 -1
  17. package/dist/esm/GValidator.production.js.map +1 -1
  18. package/dist/esm/index.development.js +4 -761
  19. package/dist/esm/index.js +4 -4
  20. package/dist/esm/shared.development.js +411 -0
  21. package/dist/esm/shared.development.js.map +1 -0
  22. package/dist/esm/shared.production.js +1 -1
  23. package/dist/esm/shared.production.js.map +1 -1
  24. package/dist/esm/useFormSelector.development.js +6 -0
  25. package/dist/esm/useFormSelector.development.js.map +1 -0
  26. package/dist/esm/useFormSelector.production.js +2 -0
  27. package/dist/esm/useFormSelector.production.js.map +1 -0
  28. package/dist/index.d.ts +260 -291
  29. package/native/dist/cjs/{gform-react-native.development.js → gform-react.development.js} +94 -79
  30. package/native/dist/cjs/gform-react.development.js.map +1 -0
  31. package/native/dist/cjs/gform-react.production.js +2 -0
  32. package/native/dist/cjs/gform-react.production.js.map +1 -0
  33. package/native/dist/cjs/index.js +8 -7
  34. package/native/dist/esm/RNGForm.development.js +105 -0
  35. package/native/dist/esm/RNGForm.development.js.map +1 -0
  36. package/native/dist/esm/RNGForm.production.js +1 -1
  37. package/native/dist/esm/RNGForm.production.js.map +1 -1
  38. package/native/dist/esm/RNGInput.development.js +83 -0
  39. package/native/dist/esm/RNGInput.development.js.map +1 -0
  40. package/native/dist/esm/RNGInput.production.js +1 -1
  41. package/native/dist/esm/RNGInput.production.js.map +1 -1
  42. package/native/dist/esm/index.development.js +2 -592
  43. package/native/dist/esm/index.js +2 -2
  44. package/native/dist/esm/shared.development.js +431 -0
  45. package/native/dist/esm/shared.development.js.map +1 -0
  46. package/native/dist/esm/shared.production.js +1 -1
  47. package/native/dist/esm/shared.production.js.map +1 -1
  48. package/native/dist/index.d.ts +183 -73
  49. package/package.json +10 -7
  50. package/dist/esm/index.development.js.map +0 -1
  51. package/native/dist/cjs/gform-react-native.development.js.map +0 -1
  52. package/native/dist/cjs/gform-react-native.production.js +0 -2
  53. package/native/dist/cjs/gform-react-native.production.js.map +0 -1
  54. package/native/dist/esm/index.development.js.map +0 -1
  55. package/native/package.json +0 -15
@@ -1,761 +1,4 @@
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, { useSyncExternalStore, useRef, useCallback, useEffect, createContext, useContext, forwardRef, useMemo, memo } 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 generateId = () => (+new Date()).toString(36) + (1 - Math.random()).toString(36).substring(2, 16);
24
- const _buildFormInitialValues = (rows = []) => {
25
- const fields = {};
26
- if (!Array.isArray(rows)) rows = [rows];
27
- for (const row of rows) {
28
- const inputConfigs = _findInputs(row);
29
- inputConfigs.forEach(config => {
30
- if (fields[config.formKey]) {
31
- console.warn(`DEV ONLY - [Duplicate Keys] - field with key '${config.formKey}' has already been defined.`);
32
- }
33
- const {
34
- required = false,
35
- max,
36
- maxLength,
37
- min,
38
- minLength,
39
- step,
40
- pattern,
41
- type = 'text',
42
- defaultValue,
43
- value,
44
- checked,
45
- defaultChecked,
46
- formKey,
47
- debounce,
48
- validatorKey
49
- } = config;
50
- const defaultProps = defaultFieldProps[type] || defaultFieldProps.text;
51
- const inputValue = value || defaultValue || checked || defaultChecked || defaultProps.value;
52
- fields[config.formKey] = {
53
- formKey,
54
- type,
55
- required,
56
- max,
57
- maxLength,
58
- min,
59
- minLength,
60
- step,
61
- pattern,
62
- value: inputValue,
63
- validatorKey,
64
- debounce,
65
- dirty: false,
66
- touched: false,
67
- gid: generateId()
68
- };
69
- Object.keys(fields[config.formKey]).forEach(key => {
70
- if (typeof fields[config.formKey][key] === 'undefined') delete fields[config.formKey][key];
71
- });
72
- });
73
- }
74
- return {
75
- fields: fields,
76
- key: generateId()
77
- };
78
- };
79
- const _findInputs = (root, total = []) => {
80
- var _root$props, _root$props2;
81
- if (!root) return total;
82
- if (Array.isArray(root)) {
83
- root.forEach(element => _findInputs(element, total));
84
- return total;
85
- }
86
- if ((_root$props = root.props) !== null && _root$props !== void 0 && _root$props.formKey) {
87
- total.push(root.props);
88
- return total;
89
- }
90
- return _findInputs((_root$props2 = root.props) === null || _root$props2 === void 0 ? void 0 : _root$props2.children, total);
91
- };
92
- const _findValidityKey = (validity, exclude = []) => {
93
- for (const key in validity) {
94
- if (exclude.includes(key)) continue;
95
- if (key !== 'valid' && validity[key]) {
96
- return key;
97
- }
98
- }
99
- };
100
- const _checkTypeMismatch = input => {
101
- var _input$value;
102
- const value = (_input$value = input.value) === null || _input$value === void 0 ? void 0 : _input$value.toString().trim();
103
- if (!value) return false;
104
- switch (input.type) {
105
- case 'email':
106
- return !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
107
- case 'url':
108
- try {
109
- new URL(value);
110
- return false;
111
- } catch (_unused) {
112
- return true;
113
- }
114
- case 'tel':
115
- return !/^\+?[0-9\s\-().]{7,}$/.test(value);
116
- default:
117
- return false;
118
- }
119
- };
120
- const hasSubmitter = form => {
121
- if (!form) return false;
122
- for (const element of form) {
123
- if (element.type === 'submit') return true;
124
- }
125
- return false;
126
- };
127
- const _checkIfFormIsValid = fields => {
128
- for (const f in fields) {
129
- if (fields[f].error) {
130
- return false;
131
- }
132
- }
133
- return true;
134
- };
135
- const _toRawData = (fields, options = {}) => {
136
- const data = {};
137
- const {
138
- include,
139
- exclude,
140
- transform
141
- } = options;
142
- if (include) {
143
- include.forEach(key => {
144
- var _fields$key;
145
- return data[key] = (_fields$key = fields[key]) === null || _fields$key === void 0 ? void 0 : _fields$key.value;
146
- });
147
- } else for (const f in fields) {
148
- data[f] = fields[f].value;
149
- }
150
- exclude === null || exclude === void 0 || exclude.forEach(key => delete data[key]);
151
- if (transform) {
152
- for (const key in transform) {
153
- var _fields$key2;
154
- const set = transform[key];
155
- data[key] = set(((_fields$key2 = fields[key]) === null || _fields$key2 === void 0 ? void 0 : _fields$key2.value) || fields[key]);
156
- }
157
- }
158
- return data;
159
- };
160
- const _toFormData = (form, options) => {
161
- if (!form) return new FormData();
162
- return new FormData(form);
163
- };
164
- function _toURLSearchParams(options) {
165
- let data;
166
- if (options) {
167
- const {
168
- exclude,
169
- include,
170
- transform
171
- } = options;
172
- if (include) {
173
- data = {};
174
- include.forEach(key => {
175
- var _this$key;
176
- return data[key] = (_this$key = this[key]) === null || _this$key === void 0 ? void 0 : _this$key.value;
177
- });
178
- } else {
179
- data = this.toRawData();
180
- exclude === null || exclude === void 0 || exclude.forEach(key => delete data[key]);
181
- }
182
- if (transform) {
183
- for (const key in transform) {
184
- var _this$key2;
185
- const set = transform[key];
186
- data[key] = set((_this$key2 = this[key]) === null || _this$key2 === void 0 ? void 0 : _this$key2.value);
187
- }
188
- }
189
- } else data = this.toRawData();
190
- return new URLSearchParams(data);
191
- }
192
- function __debounce(timeout, id) {
193
- return new Promise(resolve => {
194
- var _this$id;
195
- if ((_this$id = this[id]) !== null && _this$id !== void 0 && _this$id.timerId) clearTimeout(this[id].timerId);
196
- const timerId = setTimeout(() => resolve(), timeout);
197
- if (this[id]) {
198
- this[id].timerId = timerId;
199
- } else this[id] = {
200
- timerId
201
- };
202
- });
203
- }
204
- const _debounce = __debounce.bind({});
205
- const _extractValue = (e, unknown) => {
206
- if (e !== null && e !== void 0 && e.target) {
207
- if (Object.hasOwn(typeValueDict, e.target.type)) return e.target[typeValueDict[e.target.type]];
208
- return e.target.value;
209
- }
210
- return (e === null || e === void 0 ? void 0 : e.value) || (isObject(unknown) ? unknown.value : unknown);
211
- };
212
- const _checkResult = (handlerResult, value) => typeof handlerResult === 'boolean' ? handlerResult : typeof value === 'string' ? typeof handlerResult === 'string' ? !new RegExp(handlerResult).test(value) : !handlerResult.test(value) : false;
213
- const _merge = (target = {}, ...nodes) => {
214
- if (!nodes.length) return target;
215
- const next = nodes.shift();
216
- if (isObject(next)) {
217
- for (const key in next) {
218
- target[key] = target[key] ? _objectSpread(_objectSpread({}, target[key]), next[key]) : next[key];
219
- }
220
- }
221
- return _merge(target, ...nodes);
222
- };
223
-
224
- let handlersMap;
225
- let validityMap;
226
- {
227
- handlersMap = {
228
- minLength: 'withMinLengthMessage',
229
- maxLength: 'withMaxLengthMessage',
230
- required: 'withRequiredMessage',
231
- pattern: 'withPatternMismatchMessage',
232
- min: 'withRangeUnderflowMessage',
233
- max: 'withRangeOverflowMessage',
234
- step: 'withStepMismatchMessage',
235
- type: 'withTypeMismatchMessage'
236
- };
237
- validityMap = {
238
- tooShort: 'minLength',
239
- valueMissing: 'required',
240
- tooLong: 'maxLength',
241
- patternMismatch: 'pattern',
242
- rangeOverflow: 'max',
243
- rangeUnderflow: 'min',
244
- stepMismatch: 'step',
245
- typeMismatch: 'type'
246
- };
247
- }
248
- class GValidator {
249
- get handlers() {
250
- return this._handlers;
251
- }
252
- get constraintHandlers() {
253
- return this._constraintHandlers;
254
- }
255
- get asyncHandlers() {
256
- return this._asyncHandlers;
257
- }
258
- constructor(baseValidator) {
259
- _defineProperty(this, "_handlers", void 0);
260
- _defineProperty(this, "_constraintHandlers", void 0);
261
- _defineProperty(this, "_asyncHandlers", void 0);
262
- _defineProperty(this, "track", void 0);
263
- const baseHandlers = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.handlers) || [];
264
- const baseConstraintHandlers = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.constraintHandlers) || [];
265
- const baseHandlersAsync = (baseValidator === null || baseValidator === void 0 ? void 0 : baseValidator.asyncHandlers) || [];
266
- this._handlers = [].concat(baseHandlers);
267
- this._constraintHandlers = [].concat(baseConstraintHandlers);
268
- this._asyncHandlers = [].concat(baseHandlersAsync);
269
- {
270
- this.track = [];
271
- if (baseValidator !== null && baseValidator !== void 0 && baseValidator.track) {
272
- this.track = this.track.concat(baseValidator.track);
273
- }
274
- }
275
- }
276
- hasConstraint(constraint) {
277
- var _this$track;
278
- return ((_this$track = this.track) === null || _this$track === void 0 ? void 0 : _this$track.includes(constraint)) || false;
279
- }
280
- withRequiredMessage(message) {
281
- return this.__addConstraintValidationHandler('valueMissing', message);
282
- }
283
- withMaxLengthMessage(message) {
284
- return this.__addConstraintValidationHandler('tooLong', message);
285
- }
286
- withMinLengthMessage(message) {
287
- return this.__addConstraintValidationHandler('tooShort', message);
288
- }
289
- withPatternMismatchMessage(message) {
290
- return this.__addConstraintValidationHandler('patternMismatch', message);
291
- }
292
- withBadInputMessage(message) {
293
- return this.__addConstraintValidationHandler('badInput', message);
294
- }
295
- withRangeUnderflowMessage(message) {
296
- return this.__addConstraintValidationHandler('rangeUnderflow', message);
297
- }
298
- withRangeOverflowMessage(message) {
299
- return this.__addConstraintValidationHandler('rangeOverflow', message);
300
- }
301
- withTypeMismatchMessage(message) {
302
- return this.__addConstraintValidationHandler('typeMismatch', message);
303
- }
304
- withStepMismatchMessage(message) {
305
- return this.__addConstraintValidationHandler('stepMismatch', message);
306
- }
307
- withCustomValidation(handler) {
308
- this._handlers.push(handler);
309
- return this;
310
- }
311
- withCustomValidationAsync(handler) {
312
- this._asyncHandlers.push(handler);
313
- return this;
314
- }
315
- __addConstraintValidationHandler(validityKey, message) {
316
- if (this.track) {
317
- if (this.track.includes(validityKey)) {
318
- console.warn(`DEV ONLY - [Duplicate Handlers] - handler for '${validityKey}' has already been defined`);
319
- }
320
- this.track.push(validityKey);
321
- }
322
- this._constraintHandlers.push((input, key) => {
323
- {
324
- if (validityKey && validityMap[validityKey] && typeof input[validityMap[validityKey]] === 'undefined') {
325
- console.warn(`DEV ONLY - [Missing Prop] - the input '${input.formKey}' has registered validator for the violation '${validityKey}' but the input hasn't described the constraint '${validityMap[validityKey]}'.\nadd '${validityMap[validityKey]}' to the input props.\nexample:\n<GInput formKey='${input.formKey}' ${validityMap[validityKey]}={...} />\n\nor either remove '.${handlersMap[validityMap[validityKey]]}(...)' validation`);
326
- }
327
- }
328
- if (key === validityKey) {
329
- input.errorText = typeof message === 'string' ? message : message(input);
330
- return true;
331
- }
332
- return false;
333
- });
334
- return this;
335
- }
336
- }
337
-
338
- const useFormHandlers = (getState, setState, validators = {}, optimized = false) => {
339
- const _viHandler = (input, e) => {
340
- if (!input) return;
341
- const element = e && e.target;
342
- const hasInitialValue = !input.dirty && input.value && !input.touched;
343
- if (!element && !hasInitialValue) return;
344
- if (typeof document !== 'undefined' && (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement)) {
345
- if (!input.checkValidity) input.checkValidity = () => element.checkValidity();
346
- if (hasInitialValue) {
347
- _checkInputManually(input);
348
- _dispatchChanges(input, input.formKey);
349
- return;
350
- }
351
- element.setCustomValidity('');
352
- const exclude = input.type && (input.pattern || hasCustomValidation(input)) ? ['typeMismatch'] : [];
353
- const validityKey = _findValidityKey(element.validity, exclude);
354
- _validateInput(input, validityKey, v => element.setCustomValidity(v));
355
- if (!validityKey && input.error) {
356
- element.setCustomValidity(input.errorText || 'error');
357
- }
358
- _dispatchChanges(input, input.formKey);
359
- } else {
360
- input.checkValidity = () => _checkInputManually(input);
361
- input.checkValidity();
362
- _dispatchChanges(input, input.formKey);
363
- }
364
- };
365
- const _checkInputManually = input => {
366
- const exclude = input.type && (input.pattern || hasCustomValidation(input)) ? ['typeMismatch'] : [];
367
- let validityKey = _findValidityKey({
368
- valueMissing: input.required && !input.value || false,
369
- typeMismatch: _checkTypeMismatch(input),
370
- tooShort: input.minLength && input.value.toString().length < input.minLength || false,
371
- tooLong: input.maxLength && input.value.toString().length > input.maxLength || false,
372
- patternMismatch: input.pattern && _checkResult(input.pattern, input.value) || false,
373
- rangeUnderflow: input.min && Number(input.value) < Number(input.min) || false,
374
- rangeOverflow: input.max && Number(input.value) > Number(input.max) || false
375
- }, exclude);
376
- if (!validityKey && input.error) {
377
- validityKey = 'customError';
378
- }
379
- _validateInput(input, validityKey);
380
- return !input.error;
381
- };
382
- const _updateInputHandler = (input, e, unknown) => {
383
- input.value = _extractValue(e, unknown);
384
- _viHandler(input, e);
385
- };
386
- const _validateInput = (input, validityKey, setValidity) => {
387
- const inputValidator = validators[input.validatorKey || input.formKey] || validators['*'];
388
- {
389
- if (validityKey && !(inputValidator !== null && inputValidator !== void 0 && inputValidator.hasConstraint(validityKey))) {
390
- if (validityKey === 'typeMismatch') console.warn(`DEV ONLY - [Missing Validator] - the input '${input.formKey}' has described the constraint '${validityMap[validityKey]}' however, a correspond validator / custom validation / pattern validator are missing.\nadd '${handlersMap[validityMap[validityKey]]}' or 'withCustomValidation' or '${handlersMap[validityMap.patternMismatch]}' to the input validator.\nexample:\nconst validators: GValidators = {\n\temail: new GValidator().withPatternMismatchMessage('pattern mismatch'),\n\t...\n}\n\nor either remove the constraint '${validityMap[validityKey]}' from the input props`);else console.warn(`DEV ONLY - [Missing Validator] - the input '${input.formKey}' has described the constraint '${validityMap[validityKey]}' however, a correspond validator is missing.\nadd '${handlersMap[validityMap[validityKey]]}' to the input validator.\nexample:\nconst validators: GValidators = {\n\temail: new GValidator().withPatternMismatchMessage('pattern mismatch'),\n\t...\n}\n\nor either remove the constraint '${validityMap[validityKey]}' from the input props`);
391
- }
392
- }
393
- if (inputValidator) {
394
- __validateInput(input, inputValidator, validityKey, setValidity);
395
- }
396
- input.touched = true;
397
- };
398
- const _dispatchChanges = (changes, key) => setState(prev => {
399
- if (key) {
400
- return _objectSpread(_objectSpread({}, prev), {}, {
401
- fields: _objectSpread(_objectSpread({}, prev.fields), {}, {
402
- [key]: _objectSpread(_objectSpread({}, prev.fields[key]), changes)
403
- })
404
- });
405
- }
406
- return _objectSpread(_objectSpread({}, prev), changes);
407
- });
408
- const __validateInput = (input, inputValidator, validityKey, setValidity) => {
409
- const fields = getState().fields;
410
- for (const index in inputValidator.constraintHandlers) {
411
- const result = inputValidator.constraintHandlers[index](input, validityKey);
412
- input.error = _checkResult(result, input.value);
413
- if (input.error) return;
414
- }
415
- for (const index in inputValidator.handlers) {
416
- const result = inputValidator.handlers[index](input, fields);
417
- input.error = _checkResult(result, input.value);
418
- if (input.error) return;
419
- }
420
- input.errorText = '';
421
- if (inputValidator.asyncHandlers.length) {
422
- input.error = true;
423
- _debounce(input.debounce || 300, `${input.gid}-async`).then(() => {
424
- const validateAsync = async () => {
425
- for (const index in inputValidator.asyncHandlers) {
426
- const result = await inputValidator.asyncHandlers[index](input, fields);
427
- input.error = _checkResult(result, input.value);
428
- if (input.error) break;
429
- }
430
- if (!input.error) input.errorText = '';
431
- _dispatchChanges({
432
- error: input.error,
433
- errorText: input.errorText
434
- }, input.formKey);
435
- if (setValidity) {
436
- setValidity(input.errorText);
437
- }
438
- };
439
- validateAsync();
440
- });
441
- }
442
- };
443
- const hasCustomValidation = input => {
444
- const validator = validators[input.validatorKey || input.formKey] || validators['*'];
445
- return validator && (validator.asyncHandlers.length > 0 || validator.handlers.length > 0);
446
- };
447
- return {
448
- _updateInputHandler,
449
- _viHandler,
450
- _dispatchChanges,
451
- optimized,
452
- _createInputChecker: _checkInputManually
453
- };
454
- };
455
-
456
- const GFormContext = createContext({});
457
- const GFormContextProvider = ({
458
- children,
459
- initialState,
460
- validators,
461
- optimized
462
- }) => {
463
- const stateRef = useRef(initialState);
464
- const listeners = useRef(new Set());
465
- const setState = useCallback(updater => {
466
- stateRef.current = typeof updater === 'function' ? updater(stateRef.current) : updater;
467
- listeners.current.forEach(l => l());
468
- }, []);
469
- const handlers = useFormHandlers(() => stateRef.current, setState, validators, optimized);
470
- const getState = useCallback(() => stateRef.current, []);
471
- const subscribe = useCallback(listener => {
472
- listeners.current.add(listener);
473
- return () => listeners.current.delete(listener);
474
- }, []);
475
- useEffect(() => {
476
- for (const fieldKey in initialState.fields) {
477
- initialState.fields[fieldKey].dispatchChanges = changes => handlers._dispatchChanges(changes, fieldKey);
478
- }
479
- }, []);
480
- const store = useRef({
481
- getState,
482
- setState,
483
- subscribe,
484
- handlers
485
- });
486
- return React.createElement(GFormContext.Provider, {
487
- value: store.current
488
- }, children);
489
- };
490
- const useFormStore = () => {
491
- const store = useContext(GFormContext);
492
- if (!store) throw new Error('useGFormStore must be used within `GForm` component');
493
- return store;
494
- };
495
- const useFormSelector = selector => {
496
- const store = useFormStore();
497
- return useSyncExternalStore(store.subscribe, () => selector(store.getState()), () => selector(store.getState()));
498
- };
499
- function createSelector(selectors, combiner) {
500
- let lastArgs = [];
501
- let lastResult;
502
- return state => {
503
- const args = selectors.map(fn => fn(state));
504
- if (lastArgs.length === args.length && args.every((val, i) => val === lastArgs[i])) {
505
- return lastResult;
506
- }
507
- lastArgs = args;
508
- lastResult = combiner(...args);
509
- return lastResult;
510
- };
511
- }
512
-
513
- const _excluded$1 = ["stateRef", "onSubmit", "onChange", "onPaste", "onKeyDown", "onKeyUp", "children", "onInit"],
514
- _excluded2 = ["children", "validators", "optimized"];
515
- const FormRenderer = forwardRef((_ref, ref) => {
516
- let {
517
- stateRef,
518
- onSubmit,
519
- onChange,
520
- onPaste,
521
- onKeyDown,
522
- onKeyUp,
523
- children,
524
- onInit
525
- } = _ref,
526
- rest = _objectWithoutProperties(_ref, _excluded$1);
527
- const formRef = useRef(null);
528
- const {
529
- getState,
530
- handlers
531
- } = useFormStore();
532
- const fields = useFormSelector(state => state.fields);
533
- const refHandler = useCallback(element => {
534
- if (ref) {
535
- if (typeof ref === 'function') {
536
- ref(element);
537
- } else {
538
- ref.current = element;
539
- }
540
- }
541
- formRef.current = element;
542
- }, [ref]);
543
- const getFormState = useCallback(() => {
544
- const isFormValid = _checkIfFormIsValid(fields);
545
- const formState = _objectSpread(_objectSpread({}, fields), {}, {
546
- isValid: isFormValid,
547
- isInvalid: !isFormValid,
548
- toRawData: options => _toRawData(fields, options),
549
- toFormData: () => _toFormData(formRef.current),
550
- toURLSearchParams: _toURLSearchParams,
551
- checkValidity: function () {
552
- this.isValid = formRef.current && formRef.current.checkValidity() || false;
553
- this.isInvalid = !this.isValid;
554
- return this.isValid;
555
- },
556
- dispatchChanges: changes => handlers._dispatchChanges({
557
- fields: _merge({}, fields, changes)
558
- })
559
- });
560
- if (stateRef) stateRef.current = formState;
561
- return formState;
562
- }, [fields]);
563
- const formComponent = useMemo(() => {
564
- const state = getFormState();
565
- const formChildren = typeof children === 'function' ? children(state) : children;
566
- const _onSubmit = e => {
567
- const state = getFormState();
568
- if (state.isValid && onSubmit) {
569
- onSubmit(state, e);
570
- }
571
- };
572
- let _onPaste, _onChange, _onKeyDown, _onKeyUp;
573
- if (onPaste) {
574
- _onPaste = e => onPaste(state, e);
575
- }
576
- if (onKeyDown) {
577
- _onKeyDown = e => onKeyDown(state, e);
578
- }
579
- if (onKeyUp) {
580
- _onKeyUp = e => onKeyUp(state, e);
581
- }
582
- if (handlers.optimized) {
583
- if (onChange) {
584
- _onChange = (e, unknown) => {
585
- handlers._updateInputHandler(state[e.target.name], e, unknown);
586
- onChange(state, e);
587
- };
588
- } else {
589
- _onChange = (e, unknown) => {
590
- handlers._updateInputHandler(state[e.target.name], e, unknown);
591
- };
592
- }
593
- return React.createElement("form", _extends({}, rest, {
594
- ref: refHandler,
595
- onPaste: _onPaste,
596
- onKeyDown: _onKeyDown,
597
- onKeyUp: _onKeyUp,
598
- onBlur: e => handlers._viHandler(state[e.target.name], e),
599
- onInvalid: e => {
600
- e.preventDefault();
601
- handlers._viHandler(state[e.target.name], e);
602
- },
603
- onChange: _onChange,
604
- onSubmit: _onSubmit
605
- }), formChildren);
606
- }
607
- if (onChange) {
608
- _onChange = e => onChange(state, e);
609
- }
610
- return React.createElement("form", _extends({}, rest, {
611
- ref: refHandler,
612
- onSubmit: _onSubmit,
613
- onChange: _onChange,
614
- onPaste: _onPaste,
615
- onKeyDown: _onKeyDown,
616
- onKeyUp: _onKeyUp
617
- }), formChildren);
618
- }, [children, getFormState]);
619
- useEffect(() => {
620
- const state = getFormState();
621
- if (!hasSubmitter(formRef.current)) {
622
- console.warn(`DEV ONLY - [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 to check if the form is valid before perfoming any action, for example:\nif (formState.checkValidity()) { \n\t//do somthing\n}\n`);
623
- }
624
- if (onInit) {
625
- const changes = onInit(state);
626
- if (changes) {
627
- const _handler = _c => handlers._dispatchChanges({
628
- fields: _merge({}, state, _c)
629
- });
630
- if (changes instanceof Promise) {
631
- changes.then(_handler);
632
- } else _handler(changes);
633
- }
634
- }
635
- const fields = getState().fields;
636
- for (const fieldKey in fields) {
637
- const field = fields[fieldKey];
638
- if (!field.value) continue;
639
- handlers._viHandler(field);
640
- }
641
- }, [getFormState]);
642
- return formComponent;
643
- });
644
- const GForm = forwardRef((_ref2, ref) => {
645
- let {
646
- children,
647
- validators,
648
- optimized
649
- } = _ref2,
650
- props = _objectWithoutProperties(_ref2, _excluded2);
651
- const initialState = useMemo(() => {
652
- return _buildFormInitialValues(typeof children === 'function' ? children({}) : children);
653
- }, [children]);
654
- return React.createElement(GFormContextProvider, {
655
- key: initialState.key,
656
- initialState: initialState,
657
- validators: validators,
658
- optimized: optimized
659
- }, React.createElement(FormRenderer, _extends({
660
- ref: ref
661
- }, props), children));
662
- });
663
-
664
- const selectFields = [state => state.fields];
665
- const makeSelectFields = (keys = []) => createSelector(selectFields, fields => {
666
- const selected = keys.map(key => fields[key]).filter(Boolean);
667
- return selected.length ? selected : null;
668
- });
669
-
670
- const _excluded = ["formKey", "element", "title", "type", "fetch", "fetchDeps", "optimized", "debounce", "defaultChecked", "defaultValue", "checked", "validatorKey", "value"];
671
- const _GInput = forwardRef((_ref, ref) => {
672
- let {
673
- formKey,
674
- element,
675
- title,
676
- type = 'text',
677
- fetch,
678
- fetchDeps,
679
- optimized,
680
- debounce = 300,
681
- defaultChecked,
682
- defaultValue,
683
- checked,
684
- validatorKey,
685
- value
686
- } = _ref,
687
- rest = _objectWithoutProperties(_ref, _excluded);
688
- const inputState = useFormSelector(state => state.fields[formKey]);
689
- const store = useFormStore();
690
- const _element = useMemo(() => {
691
- let value, checked;
692
- if (type === 'checkbox') checked = inputState.value || false;else value = inputState.value || '';
693
- const _props = _objectSpread(_objectSpread({}, rest), {}, {
694
- type,
695
- name: formKey,
696
- value,
697
- checked,
698
- ref,
699
- 'aria-invalid': inputState.error,
700
- 'aria-required': inputState.required,
701
- title: title || inputState.errorText
702
- });
703
- if (!store.handlers.optimized || !optimized) {
704
- _props.onBlur = rest.onBlur ? e => {
705
- store.handlers._viHandler(inputState, e);
706
- rest.onBlur(e);
707
- } : e => {
708
- store.handlers._viHandler(inputState, e);
709
- };
710
- _props.onInvalid = rest.onInvalid ? e => {
711
- e.preventDefault();
712
- store.handlers._viHandler(inputState, e);
713
- rest.onInvalid(e);
714
- } : e => {
715
- e.preventDefault();
716
- store.handlers._viHandler(inputState, e);
717
- };
718
- _props.onChange = rest.onChange ? (e, unknown) => {
719
- store.handlers._updateInputHandler(inputState, e, unknown);
720
- rest.onChange(e);
721
- } : (e, unknown) => {
722
- store.handlers._updateInputHandler(inputState, e, unknown);
723
- };
724
- if (!inputState.touched && inputState.dispatchChanges) {
725
- _props.onFocus = rest.onFocus ? e => {
726
- rest.onFocus(e);
727
- inputState.dispatchChanges({
728
- touched: true
729
- });
730
- } : () => {
731
- inputState.dispatchChanges({
732
- touched: true
733
- });
734
- };
735
- }
736
- }
737
- if (element) {
738
- return element(inputState, _props);
739
- }
740
- return React.createElement("input", _props);
741
- }, [inputState, element]);
742
- const _fetchDeps = useFormSelector(makeSelectFields(fetchDeps));
743
- const stableFetchDeps = useMemo(() => JSON.stringify(_fetchDeps), [_fetchDeps]);
744
- useEffect(() => {
745
- if (fetch) {
746
- _debounce(debounce, `${inputState.gid}-fetch`).then(() => {
747
- const res = fetch(inputState, store.getState().fields);
748
- if (res instanceof Promise) {
749
- res.then(state => state && store.handlers._dispatchChanges(state, formKey));
750
- } else if (res) {
751
- store.handlers._dispatchChanges(res, formKey);
752
- }
753
- });
754
- }
755
- }, [stableFetchDeps]);
756
- return _element;
757
- });
758
- const GInput = memo(_GInput);
759
-
760
- export { GForm, GInput, GValidator, useFormSelector };
761
- //# sourceMappingURL=index.development.js.map
1
+ export { GForm } from './GForm.development.js';
2
+ export { GInput } from './GInput.development.js';
3
+ export { GValidator } from './GValidator.development.js';
4
+ export { useFormSelector } from './useFormSelector.development.js';