@bolttech/form-engine 3.0.0-beta.9 → 6.1.0-beta.6.1

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.
@@ -1,1616 +0,0 @@
1
- # Form Engine Core
2
-
3
- Achieve form logic re-usage with forms expressed in json format.
4
-
5
- ---
6
-
7
- 1. [Basic setup](#markdown-header-basic-setup)
8
- 2. [Step by step](#markdown-header-step-by-step)
9
- 3. [Form Features](#markdown-header-available-features)
10
- - 3.1. [Validations - Allow form to run validations in the field](#markdown-header-validations)
11
- - 3.1.1. [Named Validations](#markdown-header-validations)
12
- - 3.1.2. [Error Messages](#markdown-header-validations)
13
- - 3.1.3. [Available Validations](#markdown-header-validations)
14
- - 3.2. [Filters - Allow only what you want in the field](#markdown-header-filters)
15
- - 3.2.1. [Available formatters](#markdown-header-formatters)
16
- - 3.3. [Formatters - Style your field value with formatters](#markdown-header-formatters)
17
- - 3.4. [Masks - Modify the field value, while maintaining the original with masks](#markdown-header-masks)
18
- - 3.4.1. [Available Masks](#markdown-header-formatters)
19
- - 3.5. [Visibility conditions - Configure when to show hide/components](#markdown-header-visibility-conditions)
20
- - 3.6. [Clear fields](#markdown-header-clear-fields)
21
- - 3.7. [Api - Make api calls on certain form events](#markdown-header-api)
22
- - 3.8. [Data binding - Allow to have dynamic data in the form, binding and subscribing to form changes](#markdown-header-data-binding)
23
- - 3.8.1. [Scopes](#markdown-header-scope)
24
- - 3.8.2. [Templates](#markdown-header-templates)
25
- - 3.8.3. [varOps](#markdown-header-varops)
26
- - 3.8.4. [Direct Fields Binding](#markdown-header-direct-fields-binding)
27
- - 3.9. [State - Define component state](#markdown-header-state)
28
- - 3.10. [Group](#markdown-header-group)
29
- - 3.11. [Steps](#markdown-header-form-step)
30
-
31
- ## **Basic setup**
32
-
33
- Serve your forms in JSON to your frontend, and allow it to be agnostic of your forms logic.
34
-
35
- 3 simple steps
36
-
37
- 1. Map your components to the form (Section - Build your mappers)
38
- 2. Build json schema
39
- 3. Use it
40
-
41
- **1. BUILD MAPPERS**
42
-
43
- ```javascript
44
- import Input from 'Components/Input';
45
- import Other from 'Components/Other';
46
-
47
- const Mappings = {
48
- input: { component: Input },
49
- other: { component: Other },
50
- };
51
-
52
- const formBuilderPropsMapping = {
53
- //default prop names
54
- __default__: {
55
- getValue: 'onChange',
56
- setValue: 'value',
57
- },
58
- //component specific prop names
59
- other: {
60
- getValue: 'onChangeCallback',
61
- setValue: 'data',
62
- setErrorMessage: 'errorMessageArray',
63
- setErrorState: 'isErrored',
64
- onBlur: 'onBlurCallback',
65
- onFocus: 'onFocusCallback',
66
- onKeyUp: 'onKeyUpCallback',
67
- onKeyDown: 'onKeyDownCallback',
68
- },
69
- };
70
-
71
- export { Mappings, formBuilderPropsMapping };
72
- ```
73
-
74
- **2. BUILD SCHEMA**
75
-
76
- ```json
77
- {
78
- "components": [
79
- {
80
- "component": "",
81
- "name": "",
82
- "children": [
83
- {
84
- "component": "${componentName}",
85
- "name": "${componentFormName}",
86
- "props": {
87
- "fullWidth": true
88
- }
89
- }
90
- ]
91
- }
92
- ]
93
- }
94
- ```
95
-
96
- **USE IT (React version)**
97
-
98
- ```javascript
99
- import { Mappings, formBuilderPropsMapping } from './my-component-mappings';
100
- import { getFormSchema } from './my-api-wrapper';
101
- ...
102
- const schema = useMemo(() => getFormSchema('myInstanceContext'), []);
103
-
104
- ...
105
- <Form mappings={Mappings} propsMappings={formBuilderPropsMapping} schema={schema}>
106
- ```
107
-
108
- Nexts steps ? Checkout what you can do in the storybook with `npm run storybook` or see the best effort readme :(
109
-
110
- ## **Step by step**
111
-
112
- ### Build your mappers
113
-
114
- The form uses mappings to connect to UI components so that its easy to connect to any set of components.
115
-
116
- You can build your own mappings file or you can use the `bolttech` and if you want extend it with your set of components.
117
-
118
- In the mappings file you need to specify the component definition and a name to refer in the JSON's latter, and how the form will connect to component props.
119
-
120
- See this example
121
-
122
- ```javascript
123
- import Input from '@bit/bolttech.components.ui.input';
124
- import Checkbox from '@bit/bolttech.components.ui.checkbox';
125
- import FormGroup from '@bit/bolttech.components.common.form-group';
126
-
127
- const Mappings = {
128
- input: { component: Input },
129
- checkbox: { component: Checkbox },
130
- formGroup: { component: FormGroup },
131
- };
132
-
133
- const formBuilderPropsMapping = {
134
- input: {
135
- getValue: 'onChange',
136
- setValue: 'value',
137
- setErrorMessage: 'errorMessage',
138
- setErrorState: 'isErrored',
139
- onBlur: 'onBlur',
140
- onFocus: 'onFocus',
141
- onKeyUp: 'onKeyUp',
142
- onKeyDown: 'onKeyDown',
143
- },
144
- checkbox: {
145
- getValue: 'onChange',
146
- setValue: 'checked',
147
- },
148
- };
149
-
150
- export { Mappings, formBuilderPropsMapping };
151
- ```
152
-
153
- Here you say to the form that you can use in your JSON the names `input`, `checkbox` and `formGroup` and you tell the form how to get the props it needs from them.
154
-
155
- If you have lots of components with the same prop names, you can, and should use `__default__` key. This key allows to reuse prop names.
156
-
157
- Lets say 10 components use to `value` prop name to set the component value, and `onChange` prop name to expose value. You van set your mapper the following way
158
-
159
- ```javascript
160
- import Input from '@bit/bolttech.components.ui.input';
161
- import Checkbox from '@bit/bolttech.components.ui.checkbox';
162
-
163
- const Mappings = {
164
- input: { component: Input },
165
- checkbox: { component: Checkbox },
166
- };
167
-
168
- const formBuilderPropsMapping = {
169
- __default____: {
170
- getValue: 'onChange',
171
- setValue: 'value',
172
- },
173
- checkbox: {
174
- getValue: 'onChange',
175
- setValue: 'checked',
176
- },
177
- };
178
-
179
- export { Mappings, formBuilderPropsMapping };
180
- ```
181
-
182
- ### Setup Form provider
183
-
184
- After setting your own mappings you encapsulate your app of your form with the provider
185
-
186
- ```javascript
187
- <FormProvider mapper={Mappings} propsMapping={formBuilderPropsMapping}>
188
- {children}
189
- </FormProvider>
190
- ```
191
-
192
- **DONE. NOW build your forms**
193
-
194
- ## **Form Features**
195
-
196
- Inside the schema you can specify several actions for a field alone or that correlate and have side-effects between them.
197
-
198
- Those actions support multiple lifecycle and this must be on an action item basis:
199
-
200
- - ON_FIELD_MOUNT
201
- - ON_FIELD_CHANGE
202
- - ON_FIELD_BLUR
203
- - ON_FIELD_FOCUS
204
- - ON_FIELD_KEYUP
205
- - ON_FIELD_KEYDOWN
206
- - ON_FIELD_CLICK
207
- - ON_FIELD_CLEARED
208
- - ON_FIELD_BINDED
209
- - AFTER_FIELD_API_CALL
210
-
211
- All the actions are typed, so you will have help here seeing which lifecycles you have available
212
-
213
- Per action, you will be able to combine multiple lifecycle methods
214
-
215
- All the following features can be inserted in the same location on the schema
216
-
217
- ```json
218
- {
219
- "component": "input",
220
- "name": "fieldName",
221
- "props": {
222
- "label": "My field"
223
- }
224
- //...your feature goes here
225
- }
226
- ```
227
-
228
- ## **Validations**
229
-
230
- Like the name say, this feature lets you validate the form in the several lifecycle events of the form.
231
-
232
- ```json
233
- {
234
- "validations": {
235
- "ON_FIELD_BLUR": {
236
- "email": true
237
- },
238
- "ON_FIELD_CHANGE": {
239
- "required": true
240
- }
241
- }
242
- }
243
- ```
244
-
245
- The above example will let form know that in each change the field must have something in it, and that on blur, the value must be a email.
246
-
247
- ### Named validations
248
-
249
- There are cases where you want to build your own validation, agregating several of giving it a specific name that you can refer later
250
-
251
- ```json
252
- {
253
- "validations": {
254
- "ON_FIELD_BLUR": {
255
- "blurRequire": {
256
- "require": true
257
- }
258
- },
259
- "ON_FIELD_CHANGE": {
260
- "email": true,
261
- "changeRequire": {
262
- "require": true
263
- },
264
- "changeRestOfValidations": {
265
- "length": 50
266
- //...
267
- }
268
- }
269
- }
270
- }
271
- ```
272
-
273
- ### Error Messages
274
-
275
- You can also specify the error messages you want.
276
-
277
- ```json
278
- {
279
- "validations": {
280
- "ON_FIELD_BLUR": {
281
- "require": true
282
- },
283
- "ON_FIELD_CHANGE": {
284
- "email": true
285
- }
286
- },
287
- "errorMessages": {
288
- "default": "Default error message",
289
- "email": "Invalid e-mail"
290
- }
291
- }
292
- ```
293
-
294
- This schema part, will add messages to validations error.
295
-
296
- - Each time the field has an e-mail error it will send the "Invalid e-mail" message to the component
297
- - If there is and field error, but no message is specified, it will send what you have in `default` key. In this example, `required` error does not have message and will send "Default error message"
298
-
299
- **With named validations**
300
-
301
- If you have a named validation, you can use its name in the error messages, having better granularity on it.
302
-
303
- ```json
304
- {
305
- "validations": {
306
- "ON_FIELD_BLUR": {
307
- "blurRequire": {
308
- "require": true
309
- }
310
- },
311
- "ON_FIELD_CHANGE": {
312
- "email": true,
313
- "changeRequire": {
314
- "require": true
315
- },
316
- "changeRestOfValidations": {
317
- "length": 50
318
- //...
319
- }
320
- }
321
- },
322
- "errorMessages": {
323
- "default": "Default error message",
324
- "email": "Invalid e-mail",
325
- "blurRequire": "When you blur, this component is required",
326
- "changeRequire": "You should not leave the field blank",
327
- "changeRestOfValidations": "You are changing into an incorrect state"
328
- }
329
- }
330
- ```
331
-
332
- ### Available validations (TBD)
333
-
334
- Refer to the `TAvailableValidations` types here:
335
-
336
- ````typescript
337
- {
338
- /**
339
- * The bool function is a validation function that checks if a given value indicating whether the validation has failed or not.
340
- *
341
- * @example - in a test environment
342
- * ```
343
- * const result = bool({
344
- * validationValue: false,
345
- * });
346
- * console.log(result); // { fail: false }
347
- * ```
348
- *
349
- * @example - real json usage with field value
350
- * ```
351
- * {
352
- * validations: {
353
- * bool: '${fields.input.value}'
354
- * },
355
- * },
356
- * ```
357
- *
358
- * @example - real json usage with iVar value
359
- * ```
360
- * {
361
- * validations: {
362
- * bool: '${global.validation}'
363
- * },
364
- * },
365
- * ```
366
- */
367
- bool?: string | boolean;
368
- /**
369
- * Validation based on conditions
370
- *
371
- * @example - Compare own field to two. Origin and target default to field value
372
- * ```
373
- * conditions: {
374
- * rule: 'and',
375
- * set: [
376
- * {
377
- * condition: '===',
378
- * target: '2',
379
- * },
380
- * {
381
- * origin: '2',
382
- * condition: '===',
383
- * },
384
- * ],
385
- * },
386
- * ```
387
- * @example - Binded to Postcode field value. Must be greater than or equal two
388
- * ```
389
- * conditions: {
390
- * rule: 'or',
391
- * set: [
392
- * {
393
- * origin: '${fields.postcode.value}',
394
- * condition: '>',
395
- * target: '2',
396
- * },
397
- * {
398
- * origin: '${fields.postcode.value}',
399
- * condition: '===',
400
- * target: '2',
401
- * },
402
- * ],
403
- * },
404
- * ```
405
- * @example - Binded to Postcode field value. Must be equal to two
406
- * ```
407
- * conditions: {
408
- * rule: 'or',
409
- * set: [
410
- * {
411
- * origin: '${fields.postcode.value}',
412
- * condition: '===',
413
- * target: '2',
414
- * },
415
- * ],
416
- * },
417
- * ```
418
- */
419
- conditions?: TVAvailableValidationConditions;
420
- /**
421
- * Applies multiple validations on the given value based on the specified truth table rule.
422
- *
423
- * @param {Object} TVAvailableValidationMultipleValidations - The multiple validations object param.
424
- * @param {'AND' | 'OR' | 'NOT'} TVAvailableValidationMultipleValidations.rule - The rule to be applied based of truth table ('AND', 'OR', or 'NOT').
425
- * @param {Object} TVAvailableValidationMultipleValidations.validations - Object containing validation rules.
426
- *
427
- * @example - Validating with the expression AND where current field must have a value of 'yes' and input 2 must have a value of 'no'
428
- * ```
429
- * multipleValidations: {
430
- * rule: 'AND',
431
- * validations: {
432
- * value: 'yes',
433
- * conditions: {
434
- * rule: 'and',
435
- * set: [
436
- * {
437
- * origin: '${fields.input2.value}',
438
- * condition: '===',
439
- * target: 'no'
440
- * },
441
- * ],
442
- * },
443
- * },
444
- * },
445
- * ```
446
- * @example - Validating with the expression OR where current field must have a value of '1995-12-12' or be a valid date with regex
447
- * ```
448
- * multipleValidations: {
449
- * rule: 'OR',
450
- * validations: {
451
- * value: '1995-12-12',
452
- * regex: '^\d{4}-\d{2}-\d{2}$',
453
- * },
454
- * },
455
- * ```
456
- * @example - Validating with the expression NOT where current field doesn't have a value of '1995-12-12' and not be a valid date with regex
457
- * ```
458
- * multipleValidations: {
459
- * rule: 'NOT',
460
- * validations: {
461
- * value: '1995-12-12',
462
- * regex: '^\d{4}-\d{2}-\d{2}$',
463
- * },
464
- * },
465
- * ```
466
- */
467
- multipleValidations?: TVAvailableValidationMultipleValidations;
468
- /**
469
- * Between validations
470
- *
471
- * @example - Between ages
472
- * ``` type teste = Pick<TVAvailableValidations, 'date'>
473
- * between: {
474
- * dates: [
475
- * {
476
- * operator: '>=',
477
- * origin: {
478
- * format: 'YYYYMMDD',
479
- * intervals: {
480
- * years: 18,
481
- * },
482
- * },
483
- * },
484
- * {
485
- * operator: '<=',
486
- * origin: {
487
- * format: 'YYYYMMDD',
488
- * intervals: {
489
- * years: 75,
490
- * },
491
- * },
492
- * }
493
- * ]
494
- * }
495
- * ```
496
- *
497
- * @example - Between numbers
498
- * ```
499
- * between: {
500
- * start: '3',
501
- * end: '4',
502
- * isIncludedBoundaries: true
503
- * },
504
- * ```
505
- *
506
- */
507
- between?: {
508
- /**
509
- * Array of date validations. To make it possible, ensure that the conditions is > and < in both date validations.
510
- */
511
- dates?: TVAvailableValidations['date'][];
512
- /**
513
- * The first number of the validation. If the current value is grater than this number, the validation will pass.
514
- */
515
- start?: number;
516
- /**
517
- * The second number of the validation. If the current value is lower than this number, the validation will pass.
518
- */
519
- end?: number;
520
- /**
521
- * If it's true, the comparision is transformed to >= and <=. So, the numbers that were passed are included in the validation.
522
- */
523
- isIncludedBoundaries?: boolean;
524
- };
525
- /**
526
- * Dates validations
527
- *
528
- * @example - Dates should be different
529
- * ```
530
- * date: {
531
- * operator: '!==',
532
- * origin: {
533
- * format: 'DDMMYYYY',
534
- * },
535
- * target: {
536
- * format: 'DDMMYYYY',
537
- * value: '10/10/2001',
538
- * },
539
- * },*
540
- * ```
541
- *
542
- * @example - Compare only valid dates using intervals
543
- * ```
544
- * date: {
545
- * onlyValidDate: true,
546
- * operator: '<',
547
- * origin: {
548
- * format: 'DD/MM/YYYY',
549
- * intervals: {
550
- * years: 1,
551
- * },
552
- * },
553
- * },
554
- * ```
555
- *
556
- * @example - Should have at max 85 years
557
- * ```
558
- * {
559
- * operator: '>',
560
- * origin: {
561
- * format: 'DDMMYYYY',
562
- * value: eightyFiveYearsDate,
563
- * intervals: {
564
- * years: 85,
565
- * },
566
- * },
567
- * }
568
- * }
569
- *
570
- * ```
571
- */
572
- date?: {
573
- /**
574
- * Flag to force only valid dates. Valid dates must be of min length of 8
575
- */
576
- onlyValidDate?: boolean;
577
- /**
578
- * List of operations you can do
579
- * - between origin and target dates
580
- * - between origin and intervals
581
- */
582
- operator: TValidationDateOperators;
583
- /**
584
- * The origin configurations
585
- */
586
- origin: {
587
- /**
588
- * Origin date value
589
- */
590
- value?: string | number;
591
- /**
592
- * The available date formats
593
- */
594
- format: TValidationDateFormats;
595
- /**
596
- * Intervals to compare with the original date.
597
- *
598
- * It will use todays date for comparison.
599
- *
600
- * @example
601
- *
602
- * origin date = 10/10/2022
603
- * interval.year = 1
604
- * operator = '==='
605
- *
606
- * It will compare (10/10/2022 + 1) with the current date and check if they are the same
607
- */
608
- intervals?: {
609
- years?: number;
610
- months?: number;
611
- days?: number;
612
- };
613
- };
614
- target?: {
615
- value: string | number;
616
- format: TValidationDateFormats;
617
- };
618
- };
619
- /**
620
- * Allow to validate if the input string is a valid date format
621
- */
622
- validDate?: TValidationDateFormats;
623
- /**
624
- * Allow to define a maximum length for the input to have no error
625
- */
626
- length?: number;
627
- /**
628
- * Will look into the input length and send an error if if not greater than this value
629
- */
630
- greaterThan?: number | string;
631
-
632
- /**
633
- * Specifies a regular expression pattern that the value should match.
634
- */
635
- regex?: string;
636
-
637
- /**
638
- * Specifies the maximum length of the value (if it's a string).
639
- */
640
- maxLength?: number;
641
-
642
- /**
643
- * Specifies the minimum length of the value (if it's a string).
644
- */
645
- minLength?: number;
646
-
647
- /**
648
- * Specifies whether the field is required.
649
- */
650
- required?: boolean;
651
-
652
- /**
653
- * Specifies that the value should contain only letters.
654
- */
655
- onlyLetters?: boolean;
656
-
657
- /**
658
- * Specifies a value that the field should match.
659
- */
660
- value?: string | number | boolean;
661
-
662
- /**
663
- * Specifies that the field should not be empty.
664
- */
665
- notEmpty?: boolean;
666
-
667
- /**
668
- * A callback function that performs custom validation on the value.
669
- * @param value - The value to be validated.
670
- * @returns An object with validation results.
671
- */
672
- callback?(value: string | number): { fail: boolean; errorMessage?: string };
673
-
674
- /**
675
- * Specifies a numeric range for the value.
676
- */
677
- numericRange?: { start: number | string; end: number | string };
678
-
679
- /**
680
- * Specifies whether the value should be a number.
681
- */
682
- isNumber?: boolean;
683
-
684
- /**
685
- * Specifies that the field should not have extra spaces.
686
- */
687
- hasNoExtraSpaces?: boolean;
688
-
689
- /**
690
- * Specifies that the value should be an email address.
691
- */
692
- email?: boolean;
693
-
694
- /**
695
- * Specifies that the value should be less than a given number or string.
696
- */
697
- lessThan?: number | string;
698
-
699
- /**
700
- * Specifies that the value should be a sequential number.
701
- */
702
- sequentialNumber?: boolean;
703
-
704
- /**
705
- * Specifies that the value should not contain repeated numbers.
706
- */
707
- repeatedNumbers?: boolean;
708
-
709
- /**
710
- * Specifies that the value should be a URL.
711
- */
712
- url?: boolean;
713
-
714
- /**
715
- * Specifies a path error type.
716
- */
717
- path?: TPathError;
718
-
719
- /**
720
- * Specifies that the value should be a valid credit card number.
721
- */
722
- isCreditCard?: string[];
723
-
724
- /**
725
- * Specifies that the value should be a valid credit card number with a specific length.
726
- */
727
- isCreditCardAndLength?: string[];
728
-
729
- /**
730
- * Specifies that the value should match a credit card code with available options.
731
- */
732
- isCreditCodeMatch?: { numberCard: string; availableOptions: string[] };
733
-
734
- /**
735
- * Specifies custom validation options for the field.
736
- */
737
- customValidation?: ICustomValidationValue[];
738
-
739
- /**
740
- * Specifies that spaces are not allowed in the field.
741
- */
742
- notAllowSpaces?: true;
743
-
744
- /**
745
- * Specifies that the value should be in a predefined list of values.
746
- */
747
- isInTheList?: string[] | number[] | string;
748
-
749
- /**
750
- * Specifies field validation rules for nested fields.
751
- */
752
- fields?: {
753
- /**
754
- * The rule for validating nested fields (e.g., 'every').
755
- */
756
- rule: 'every';
757
-
758
- /**
759
- * An array of nested field validation configurations.
760
- */
761
- set: {
762
- /**
763
- * The binding for the nested field.
764
- */
765
- bind: string;
766
-
767
- /**
768
- * The field name for the nested field.
769
- */
770
- fieldName: string;
771
-
772
- /**
773
- * Validation options for the nested field, excluding the 'fields' property.
774
- */
775
- validations: Omit<TVAvailableValidations, 'fields'>;
776
- }[];
777
- };
778
-
779
- /**
780
- * Specifies that the value should be existed.
781
- */
782
- exists?: string | number ;
783
- }
784
- ````
785
-
786
- ## **Formatters**
787
-
788
- Formatting a field means mutating the field value to a given... format.
789
-
790
- This options will allow you to force a give field to have the format you whant while the user is performing some action on the form.
791
-
792
- **NOTE** - When receiving the values of the form, you will have the value with the specified format, not the raw value the user entered
793
-
794
- You have several formatters. THe following example shows splitter that is a more generic one, allowing you to split the input text
795
-
796
- **BIG NOTE** - Formatters won't execute when a value is deleting (eg. user pressed backspace to delete a character), to execute on every
797
- value change, use masks instead
798
-
799
- ```json
800
- {
801
- "formatters": {
802
- "ON_FIELD_MOUNT": {
803
- "splitter": [
804
- {
805
- "position": 2,
806
- "value": "/"
807
- },
808
- {
809
- "position": 5,
810
- "value": "/"
811
- }
812
- ]
813
- }
814
- }
815
- }
816
- ```
817
-
818
- The above example will split your word in position 2 and 5, adding there the `/`. This will give you a date format like `10/10/1987` (you would have to limit the input length. More on that on FILTERS)
819
-
820
- ### Available Formatters (TBD)
821
-
822
- Refer to the types on `TSchema`
823
-
824
- #### Regex
825
-
826
- Specifies a regular expression pattern that the value should match to be replaced.
827
-
828
- ```json
829
- {
830
- "formatters": {
831
- "ON_FIELD_MOUNT": {
832
- "regex": "[0-9]"
833
- }
834
- }
835
- }
836
- ```
837
-
838
- #### Callback
839
-
840
- Specifies a function that will format the field
841
-
842
- ```typescript
843
- const removeDots = (value: string | number): string | number => {
844
- return value.split('.').join('');
845
- };
846
-
847
- const formatterInstance = {
848
- formatters: {
849
- ON_FIELD_CHANGE: {
850
- callback: removeDots,
851
- },
852
- },
853
- };
854
- ```
855
-
856
- ## Masks
857
-
858
- Mask has the same functionality of formatter, but keed the original value for your program. Think of it like the password mask. You input something into your text input, mask that something with `*` but you need to read the original value. FOr Eg.
859
-
860
- ```json
861
- {
862
- "masks": {
863
- "ON_FIELD_BLUR": {
864
- "replaceAll": "*"
865
- },
866
- "ON_FIELD_FOCUS": {
867
- "cleanMask": true
868
- }
869
- }
870
- }
871
- ```
872
-
873
- In this example, you will
874
-
875
- - Mask a given text input from for example `123345` to `******`
876
- - On Focus , you tell form to clean the mask with `cleanMask` directive.
877
-
878
- ### Available Masks (TBD)
879
-
880
- Refer to the types on `TSchema`
881
-
882
- #### Callback
883
-
884
- Specifies a function that will format the field
885
-
886
- ```typescript
887
- const removeDots = (value: string | number): string | number => {
888
- return value.split('.').join('');
889
- };
890
-
891
- const formatterInstance = {
892
- formatters: {
893
- ON_FIELD_CHANGE: {
894
- callback: removeDots,
895
- },
896
- },
897
- };
898
- ```
899
-
900
- ## **Filters**
901
-
902
- Filters very predictable and work like the word says, they filter a given word to a given patter/directive.
903
-
904
- Lets say you want a field to accept only numbers and with a max length o X.
905
-
906
- ```json
907
- {
908
- "filter": {
909
- "ON_FIELD_CHANGE": {
910
- "length": 4,
911
- "isNumber": true
912
- }
913
- }
914
- }
915
- ```
916
-
917
- This example will let you do just that. Only numbers and max length of 4
918
-
919
- ### Available filters (TBS)
920
-
921
- Refer to the types on `TSchema`
922
-
923
- ## Visibility conditions
924
-
925
- ### Field level
926
-
927
- Sometimes you want to hide other fields based on certain conditions.
928
-
929
- That is what this feature does.
930
-
931
- Eg: You want to hide another field, when a given field `originalField` has a given value on it.
932
-
933
- ```json
934
- [
935
- {
936
- "name": "originalField",
937
- "component": "checkbox",
938
- "visibilityConditions": {
939
- "ON_FIELD_MOUNT": [
940
- {
941
- "validations": {
942
- "value": "Yes"
943
- },
944
- "fieldName": "targetField"
945
- }
946
- ],
947
- "ON_FIELD_CHANGE": [
948
- {
949
- "validations": {
950
- "value": "Yes"
951
- },
952
- "fieldName": "targetField"
953
- }
954
- ]
955
- },
956
- "props": {
957
- //...
958
- }
959
- },
960
- {
961
- "name": "targetField",
962
- "component": "input",
963
- "props": {
964
- //...
965
- }
966
- }
967
- ]
968
- ```
969
-
970
- This example tells form to
971
-
972
- - On mount check if `originalField` has the value `Yes`
973
- - If it put the `targetField` visible
974
- - Otherwise, make it invisible
975
-
976
- You can also for each visibility condition, apply it to multiple field names with `fieldNames` key that will accept an array.
977
-
978
- ```json
979
- {
980
- "visibilityConditions": {
981
- "ON_FIELD_MOUNT": [
982
- {
983
- "validations": {
984
- "value": "Yes"
985
- },
986
- "fieldNames": ["targetFieldOne", "targetFieldTwo"]
987
- }
988
- ]
989
- }
990
- }
991
- ```
992
-
993
- **NOTE** - When the field is hidden using this feature, the form will not try to validate it and will not be accounted to the general form state
994
-
995
- ### Form Level
996
-
997
- You can also use those in form level.
998
-
999
- ```javascript
1000
- <Form
1001
- iVars={{ roofUpdated: state }}
1002
- initialValues={{ roofUpdatedYear: 'diogos' }}
1003
- schema={{
1004
- visibilityConditions: {
1005
- ON_FORM_MOUNT: [
1006
- {
1007
- validations: {
1008
- value: '${global.roofUpdated}',
1009
- },
1010
- fieldName: 'roofUpdatedYear',
1011
- },
1012
- ],
1013
- ON_FIELD_CHANGE: [
1014
- {
1015
- validations: {
1016
- value: 'abc',
1017
- },
1018
- fieldName: 'roofUpdatedYear',
1019
- },
1020
- ],
1021
- },
1022
- components: [{...}],
1023
- }}
1024
- />
1025
- ```
1026
-
1027
- in the above example we are applying the rule:
1028
-
1029
- - in form mount we will hide the value when the `roofUpdatedYear` equals to the iVar `roofUpdated`
1030
- - in each field change we will hide the value when the `roofUpdatedYear` equals to `abc`
1031
- - also you can use the prop `rule` to decide what type of validations rules to execute (and == every | or == some)
1032
- - if you want to show an field only if all or at least one validation is true, use `showOnlyIfTrue` property.
1033
-
1034
- ## Clear Fields
1035
-
1036
- Guess what... THis will clear one or more form fields :)
1037
-
1038
- Uses the same mechanism of VISIBILITY CONDITIONS.
1039
-
1040
- Let's say you want to clear a given field when `originalField` has a given value.
1041
-
1042
- ```json
1043
- {
1044
- "clearFields": {
1045
- "ON_FIELD_CHANGE": [
1046
- {
1047
- "validations": {
1048
- "value": "Yes"
1049
- },
1050
- "field": "targetValue",
1051
- "clearedValue": false
1052
- }
1053
- ]
1054
- }
1055
- }
1056
- ```
1057
-
1058
- When form fires ON_CHANGE this will have the effect of having the field `targetValue` with the value `false` if `originalField` has value `Yes`.
1059
-
1060
- Just like before, you can specify multiple fields with `fields` key for the same rule.
1061
-
1062
- ```json
1063
- {
1064
- "clearFields": {
1065
- "ON_FIELD_CHANGE": [
1066
- {
1067
- "validations": {
1068
- "value": "Yes"
1069
- },
1070
- "fields": ["targetValue"],
1071
- "clearedValue": false
1072
- }
1073
- ]
1074
- }
1075
- }
1076
- ```
1077
-
1078
- Additionally, you can specify multiple props to be changed or cleared from the fields that you specified before using `clearedProps`.
1079
- Each prop will be changed using the respective field. For example, if I have `fields['input', 'checkbox']` then I need to change the input label
1080
- I can send it as `clearedProps: [{ label: 'value' }]` or `clearedProps: { label: 'value' }`. And only input props will be changed.
1081
- It's useful when we have some API calls whose response will be used as a prop value in the component.
1082
-
1083
- ```json
1084
- {
1085
- "clearFields": {
1086
- "ON_FIELD_CHANGE": [
1087
- {
1088
- "validations": {
1089
- "value": "Yes"
1090
- },
1091
- "field": "targetValue",
1092
- "clearedValue": false,
1093
- "defaultClearedValue": true,
1094
- "defaultClearedProps": {
1095
- "disabled": false
1096
- }
1097
- }
1098
- ]
1099
- }
1100
- }
1101
- ```
1102
-
1103
- If you want to set a value when the validation passes you can set `defaultClearedValue` prop on the event to set a value on the cleared field.
1104
- Useful after an API call to set a default response value or a value stored earlier.
1105
- You can also set a `defaultClearedProps` attribute to change the props of the component if the validation passes.
1106
-
1107
- For definition clearValues runs validations on the target field and not on the field it is declaring.
1108
- Therefore, you can set `useCurrentFieldValidation` prop with true if you want validations to be performed on the current field.
1109
-
1110
- > Remember, clearValues only performs `rehydration` on the target field, that is, if your target field has an api call, for example,
1111
- > you must listen to the `ON_FIELD_CLEARED` event to execute such a call on the target field.
1112
-
1113
- ## Api
1114
-
1115
- This one will let you instruct form to call a give API at a given lifecycle method
1116
-
1117
- ```json
1118
- {
1119
- "api": {
1120
- "ON_FIELD_CHANGE": [
1121
- {
1122
- "blockRequestWhenInvalid": true,
1123
- "method": "GET",
1124
- "url": "https://api.chucknorris.io/jokes/random",
1125
- "scope": "chuck"
1126
- }
1127
- ]
1128
- }
1129
- }
1130
- ```
1131
-
1132
- The above example will make form to call the API specified when the field where we gave the directory changes.
1133
-
1134
- ### Keys
1135
-
1136
- | key | type | Description |
1137
- | ----------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1138
- | blockRequestWhenInvalid | boolean | Specify if this call should be blocked when the field is invalid (due to validations) |
1139
- | method | string | HTTP verb. Get, Post, Put or delete |
1140
- | url | string | The api url |
1141
- | scope | string | This lets you put the api result inside the form scope in the given key. THis will allow to use the call result latter on on some field |
1142
- | body | object | Body to send to the API |
1143
- | headers | object | Api headers |
1144
- | fieldValueAsParams | object | An object with key (name of the field in the form) and value (name that I want to be in the query, which if nothing is passed, uses the name of the field as the key) and then it transforms it into a query string |
1145
- | fieldValueAsPathParams | array of strings | an array of field names where he uses it as a key to capture the value and transforms it into path param |
1146
- | debounceTime | number | Allow you to debounce the api call by X seconds |
1147
- | preConditions | TValidations | Allow you to specify validations that should not fail in order to call the API |
1148
-
1149
- ### PreConditions
1150
-
1151
- You can specify the pre-conditions that need to be met, in order for the request to start.
1152
-
1153
- ```json
1154
- {
1155
- "api": {
1156
- "ON_FIELD_CHANGE": [
1157
- {
1158
- "method": "GET",
1159
- "url": "https://api.chucknorris.io/jokes/random",
1160
- "scope": "chuck",
1161
- "preConditions": {
1162
- "required": true,
1163
- "value": "run"
1164
- }
1165
- }
1166
- ]
1167
- }
1168
- }
1169
- ```
1170
-
1171
- In the above example, the api specified will only be called
1172
-
1173
- 1. When field has changes
1174
- 2. When field has values (required validation)
1175
- 3. When the field value is "run"
1176
-
1177
- ### FieldValueAsParams
1178
-
1179
- You can add as many query parameters as you want, but remember that it will search for a field that exists, otherwise it will not be included in the call.
1180
-
1181
- ```json
1182
- {
1183
- "api": {
1184
- "ON_FIELD_CHANGE": [
1185
- {
1186
- "method": "GET",
1187
- "url": "https://api.chucknorris.io/jokes",
1188
- "scope": "chuck",
1189
- "fieldValueAsParams": {
1190
- "input": "name",
1191
- "date": ""
1192
- }
1193
- }
1194
- ]
1195
- }
1196
- }
1197
- ```
1198
-
1199
- From the example above, the call will have the following structure:
1200
-
1201
- ```bash
1202
- # GET https://api.chucknorris.io/jokes?name=random&date=2013-20-01
1203
- ```
1204
-
1205
- When one of the parameters has a key but no value, the key will be reused in the query string.
1206
-
1207
- ### FieldValueAsPathParams
1208
-
1209
- With this parameter, it is possible to use the value of any form field as path param for the http call, as follows:
1210
-
1211
- ```json
1212
- {
1213
- "api": {
1214
- "ON_FIELD_CHANGE": [
1215
- {
1216
- "method": "GET",
1217
- "url": "https://api.chucknorris.io/jokes",
1218
- "scope": "chuck",
1219
- "fieldValueAsPathParams": ["input", "date"]
1220
- }
1221
- ]
1222
- }
1223
- }
1224
- ```
1225
-
1226
- From the example above, the call will have the following structure:
1227
-
1228
- ```bash
1229
- # GET https://api.chucknorris.io/jokes/random/2013-20-01
1230
- ```
1231
-
1232
- So far he only puts one after the other, he still doesn't have the intelligence to choose where to put each.
1233
-
1234
- ## Data binding
1235
-
1236
- Form has a functionality to allow you to build your logic inside the schema via templating.
1237
-
1238
- You can emit and register to data between fields. For example, in the following example field `one` will register to changes on field `two` and its label will have the field `two` value. This is accomplished with [scopes](#scope).
1239
-
1240
- ```json
1241
- [
1242
- {
1243
- "name": "one",
1244
- "component": "input",
1245
- "props": {
1246
- "label": "${fields.two.value}"
1247
- }
1248
- },
1249
- {
1250
- "name": "one",
1251
- "component": "input",
1252
- "props": {
1253
- //...
1254
- }
1255
- }
1256
- ]
1257
- ```
1258
-
1259
- The subscription is done using the template first keys. In this case `fields` and `two`. Telling the engine that anytime the namespace `fields` and key `two` changes it should fire a notification to anyone interested. In this case, field `one` is interested
1260
-
1261
- ### Scope
1262
-
1263
- For templating to work, form relies on scope. The definition of scope is just a datastructures that has multiple keys each one with their context. The following table explain the namespaces
1264
-
1265
- | namespace | description |
1266
- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1267
- | global | This namespace contains all the data that comes from the client implementing the Form and is injected in iVars |
1268
- | fields | Automatically generated scope. This namespace contains all the fields with everything that is done in them per field. Eg: value, errors, visible, mask etc. Refer to the types for more info |
1269
- | api | This scope is where you can store the api responses with the api scope key. |
1270
- | hooks | This one is retrieved by the hooks configured on the client |
1271
- | configs | All the configs that the client gave to the form, will be stored here |
1272
-
1273
- Templating basically allows a given component to subscribe to any scope change, be notified and changed according to that. In the following example, the component named `make` is subscribed to `api` namespace on `data` key.
1274
-
1275
- ```json
1276
- {
1277
- "name": "make",
1278
- "component": "dropdown",
1279
- "props": {
1280
- "id": "make",
1281
- "name": "make",
1282
- "label": "Make",
1283
- "placeholder": "",
1284
- "options": "${api.makes.data||[]}"
1285
- }
1286
- }
1287
- ```
1288
-
1289
- This means that, anytime that `api.makes.data` changes (done by api action with scope = data), this component will be injected with its value on the `options` key. It also has a default value of empty array `...data||[]}`.
1290
-
1291
- If you want you can even nest templating also. Next example we will access to `global` namespace on `name` key. But we will access the prop dynamically from the field named `myfield` value
1292
-
1293
- ```json
1294
- {
1295
- "component": "input",
1296
- "name": "destination",
1297
- "props": {
1298
- "name": "destination",
1299
- "label": "Dynamic -> ${global.name.${fields.myfield.value||test}}"
1300
- }
1301
- }
1302
- ```
1303
-
1304
- This will result in the following. Assume we have scope like
1305
-
1306
- ```json
1307
- {
1308
- "global": {
1309
- "name": {
1310
- "test": "test",
1311
- "other": "other"
1312
- }
1313
- }
1314
- }
1315
- ```
1316
-
1317
- It will access `global.name.test` since we have the default value as test and there is no data in fields scope. The end result would be _"Dynamic -> test"_
1318
-
1319
- But right after input on the form field named `myfield`, its scope will be populated
1320
-
1321
- ```json
1322
- {
1323
- "global": {
1324
- "name": {
1325
- "test": "test",
1326
- "other": "other"
1327
- }
1328
- },
1329
- "fields": {
1330
- "myfield": {
1331
- "value": "other"
1332
- //...
1333
- }
1334
- }
1335
- }
1336
- ```
1337
-
1338
- In this case would access `global.name.other` and the final result would be _"Dynamic -> other"_
1339
-
1340
- ### Templates
1341
-
1342
- We talked about templates, but let's go a step further. THe definition of template, is a just a string that has a given prefix and suffix like `${...}`.
1343
-
1344
- Whatever comes inside the delimiters will be later extracted by the engine and mapped with the current scope in order to find a replacement value.
1345
-
1346
- The only limitation is that the template must be a string representing an object path. That object path will be looked for in the [scope](#scope) like `#{api.myapicall.response.data.value}`.
1347
-
1348
- **Default values**
1349
-
1350
- You can set template default values with `||` like `${fields.foo.value||default-value}`. This will lead to, if the scope has value in `fields.foo` set the value in template value, otherwise set the string `default-value`.
1351
- You can also use as many values as you want as defaults. Only what is valid and has a value will go into the field, otherwise it will be undefined.
1352
-
1353
- **Template nesting**
1354
-
1355
- You can also nest multiple templates reaching extreme situations. For example
1356
-
1357
- `${fields.${gloval.fieldname||foo}.value||novalue}`
1358
-
1359
- This example will give you the following possible replacements:
1360
-
1361
- - If `global.fieldname` exists and has value `bar` for example, and form `bar` field contains value lets say value 2 - Output will be 2
1362
- - If `global.fieldname` exists and has value `bar` for example, and form `bar` field does not contain value - Output will be non value
1363
- - If `global.fieldname` does not exists , and form `foo` field does not contain value - Output will be non value
1364
- - If `global.fieldname` does not exists , and form `foo` field contains value lets say value 3 - Output will be 3
1365
-
1366
- ### VarOps
1367
-
1368
- Templates are already a great power of form-engine, but we can go further allowing operations to be specified in the schema. Those operations are all under `varOps` (variable operations).
1369
-
1370
- ```json
1371
- {
1372
- "component": "input",
1373
- "name": "password",
1374
- "errorMessages": {
1375
- "required": "Password is required",
1376
- "value": "Error value must be varOps.concatenate(${fields.email.value||0},${fields.email2.value||0})"
1377
- },
1378
- "validations": {
1379
- "ON_FIELD_CHANGE": {
1380
- "required": true,
1381
- "value": "varOps.concatenate(${fields.email.value||0},${fields.email2.value||0})"
1382
- }
1383
- },
1384
- "props": {
1385
- "variants": "default_border",
1386
- "placeholder": "Please enter your password",
1387
- "label": "Password"
1388
- }
1389
- }
1390
- ```
1391
-
1392
- In the example the validation value comes from a `varOps`. This example uses the `concatenate` operations exposed by the engine.
1393
-
1394
- Here this field (`password`) will register with [templating](#templates) to field `email` and `email2`. Meaning, each time they change this field schema will be recomputed with what changed to replace the needed values.
1395
-
1396
- When this happens, lets say `email` has value foo and `email2` value bar. The `varOp` concatenate will be called with the correct field replaced values
1397
-
1398
- ```javascript
1399
- varOps.concatenate('foo', 'bar');
1400
- ```
1401
-
1402
- This will map to an operation function and the function return value will be replaced by the varOps like
1403
-
1404
- ```json
1405
- {
1406
- "validations": {
1407
- "ON_FIELD_CHANGE": {
1408
- "required": true,
1409
- "value": "foo_bar"
1410
- }
1411
- }
1412
- }
1413
- ```
1414
-
1415
- Since we are already using [templates](#templates) to run our varOps and subscribe to changes, also the error message string subscribed to the operation result. In this example we would endue with the following messages.
1416
-
1417
- ```json
1418
- {
1419
- "errorMessages": {
1420
- "required": "Password is required",
1421
- "value": "Error value must be foo_bar"
1422
- }
1423
- }
1424
- ```
1425
-
1426
- PS: Don't's forget that we still have the default values provided with [templates](#templates) and the rules are the same
1427
-
1428
- #### Available VarOps
1429
-
1430
- - concatenate(arg1,arg2)
1431
- - add(arg1,arg2)
1432
- - subtract(arg1,arg2)
1433
-
1434
- ### Direct fields binding
1435
-
1436
- You can change multiple field values and properties with `bindFields` using the form ref in the react adapter, example:
1437
-
1438
- ```js
1439
- {
1440
- const ref = useRef < TFormRefActions > null;
1441
-
1442
- return (
1443
- <>
1444
- <Form id="form" ref={ref} schema={foo} />
1445
- </>
1446
- );
1447
- }
1448
-
1449
- const handleFields = (input1: string, input2: number) =>
1450
- ref.current?.bindFields({
1451
- input1: {
1452
- value: input1,
1453
- props: {
1454
- disabled: false,
1455
- },
1456
- },
1457
- input2: {
1458
- value: input2,
1459
- props: {
1460
- disabled: true,
1461
- },
1462
- },
1463
- });
1464
- ```
1465
-
1466
- All schema fields that has the same name as the passed keys will have his values/properties changed and validations executed
1467
-
1468
- > Also, you can listen to the `ON_FIELD_BINDED` event to execute any handler on the target field.
1469
-
1470
- ## State
1471
-
1472
- This key will allow you to set up some initial state on the field.
1473
-
1474
- ### hidden
1475
-
1476
- Hidden prop on state, will turn your field visible or invisible
1477
-
1478
- ```json
1479
- {
1480
- "state": {
1481
- "hidden": true
1482
- }
1483
- }
1484
- ```
1485
-
1486
- This will be reflected on the field scope.
1487
-
1488
- ### ignoreValue
1489
-
1490
- Ignore component value prop on state, will control whether the property with the formatted value will be created.
1491
-
1492
- ```json
1493
- {
1494
- "state": {
1495
- "ignoreValue": true
1496
- }
1497
- }
1498
- ```
1499
-
1500
- Very useful when using group ownership, to limit who will actually send the value.
1501
-
1502
- ## Rehydrate
1503
-
1504
- **DEPRECATED, you can accomplish it with templating (previous section)**
1505
-
1506
- It lets you rehydrate a given field
1507
-
1508
- ```json
1509
- {
1510
- "rehydrate": {
1511
- "ON_FIELD_CHANGE": [
1512
- {
1513
- "validations": {
1514
- "required": true
1515
- },
1516
- "fields": ["destination"]
1517
- }
1518
- ]
1519
- },
1520
- "component": "dropdown",
1521
- "name": "originalField"
1522
- }
1523
- ```
1524
-
1525
- The api is pretty much like visibility conditions. The above example will rehydrate the `destination` field when field with the directive (_originalField_) meets the validations configured
1526
-
1527
- ## Group
1528
-
1529
- In form, we can correlate fields into a single field name. This is called the group functionality.
1530
-
1531
- Say you have two checkboxes and want the selected value. You can use `group` for that
1532
-
1533
- ```json
1534
- [
1535
- {
1536
- "name": "checkOne",
1537
- "group": "checkedGroup",
1538
- "component": "checkbox",
1539
- "props": {
1540
- //...
1541
- }
1542
- },
1543
- {
1544
- "name": "checkTwo",
1545
- "group": "checkedGroup",
1546
- "component": "checkbox",
1547
- "props": {
1548
- //...
1549
- }
1550
- }
1551
- ]
1552
- ```
1553
-
1554
- This example will store the selected value of the checkbox in the `checkedGroup` and will then be sent to the client.
1555
-
1556
- ## Form Step
1557
-
1558
- In the form it is possible to use it as steps. With this it is possible to have more than one form in just one schema.
1559
-
1560
- For example, if you implement something like:
1561
-
1562
- ```js
1563
- {
1564
- components: [
1565
- { component: '', name: 'step1', children: [] },
1566
- { component: '', name: 'step2', children: [] },
1567
- { component: '', name: 'step3', children: [] },
1568
- ];
1569
- }
1570
- ```
1571
-
1572
- You can control the go back and forth event from the [onClick](#props) event of a button inside one of the forms using the form reference.
1573
- Or Simply using the form reference in a button outside the form, for example:
1574
-
1575
- ```js
1576
- {
1577
- const ref = useRef < TFormRefActions > null;
1578
-
1579
- return (
1580
- <Form id="form" ref={ref} onClick={() => ref.current?.stepForward()} />
1581
- );
1582
- }
1583
-
1584
- // --------------------- OR --------------------- //
1585
-
1586
- {
1587
- const ref = useRef < TFormRefActions > null;
1588
-
1589
- return (
1590
- <>
1591
- <Form id="form" ref={ref} />
1592
- <button onClick={ref.current?.stepBack()} />
1593
- </>
1594
- );
1595
- }
1596
- ```
1597
-
1598
- However, it is possible to choose which step you want to go or go back, using the numerical index or simply the name of the step you want, for example:
1599
-
1600
- ```js
1601
- () => ref.current?.stepForward(2);
1602
- // --------------- OR -------------- //
1603
- () => ref.current?.stepForward('step3');
1604
-
1605
- () => ref.current?.stepBack(0);
1606
- // --------------- OR -------------- //
1607
- () => ref.current?.stepBack('step1');
1608
- ```
1609
-
1610
- Additionally, you can use a `step` method provided by form reference to easily set a desired step using the `onFormMount` event. For example:
1611
-
1612
- ```js
1613
- <Form ref={ref} schema={schema} onFormMount={() => ref.current?.step(1)} />
1614
- ```
1615
-
1616
- Remembering that this method has a mandatory index parameter, which can either be the step index number in the array or simply its defined string name in the schema.