@bolttech/form-engine-core 0.0.1-beta.16 → 0.0.1-beta.18

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.
package/README.md CHANGED
@@ -7,6 +7,7 @@ Achieve form logic re-usage with forms expressed in json format.
7
7
  1. [Basic setup](#markdown-header-basic-setup)
8
8
  2. [Step by step](#markdown-header-step-by-step)
9
9
  3. [Form Features](#markdown-header-available-features)
10
+
10
11
  - 3.1. [Validations - Allow form to run validations in the field](#markdown-header-validations)
11
12
  - 3.1.1. [Named Validations](#markdown-header-validations)
12
13
  - 3.1.2. [Error Messages](#markdown-header-validations)
@@ -277,16 +278,18 @@ You can also specify the error messages you want.
277
278
  ```json
278
279
  {
279
280
  "validations": {
280
- "ON_FIELD_BLUR": {
281
- "require": true
282
- },
283
- "ON_FIELD_CHANGE": {
281
+ "methods": {
282
+ "require": true,
284
283
  "email": true
284
+ },
285
+ "eventMessages": {
286
+ "ON_FIELD_BLUR": ["required"],
287
+ "ON_FIELD_CHANGE": ["email"]
288
+ },
289
+ "messages": {
290
+ "default": "Default error message",
291
+ "email": "Invalid e-mail"
285
292
  }
286
- },
287
- "errorMessages": {
288
- "default": "Default error message",
289
- "email": "Invalid e-mail"
290
293
  }
291
294
  }
292
295
  ```
@@ -303,28 +306,29 @@ If you have a named validation, you can use its name in the error messages, havi
303
306
  ```json
304
307
  {
305
308
  "validations": {
306
- "ON_FIELD_BLUR": {
309
+ "methods": {
307
310
  "blurRequire": {
308
311
  "require": true
309
- }
310
- },
311
- "ON_FIELD_CHANGE": {
312
+ },
312
313
  "email": true,
313
314
  "changeRequire": {
314
315
  "require": true
315
316
  },
316
317
  "changeRestOfValidations": {
317
318
  "length": 50
318
- //...
319
319
  }
320
+ },
321
+ "eventMessages": {
322
+ "ON_FIELD_BLUR": ["blurRequire"],
323
+ "ON_FIELD_CHANGE": ["email", "changeRequire", "changeRestOfValidations"]
324
+ },
325
+ "messages": {
326
+ "default": "Default error message",
327
+ "email": "Invalid e-mail",
328
+ "blurRequire": "When you blur, this component is required",
329
+ "changeRequire": "You should not leave the field blank",
330
+ "changeRestOfValidations": "You are changing into an incorrect state"
320
331
  }
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
332
  }
329
333
  }
330
334
  ```
@@ -624,10 +628,6 @@ Refer to the `TAvailableValidations` types here:
624
628
  * Allow to define a maximum length for the input to have no error
625
629
  */
626
630
  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
631
 
632
632
  /**
633
633
  * Specifies a regular expression pattern that the value should match.
@@ -669,7 +669,7 @@ Refer to the `TAvailableValidations` types here:
669
669
  * @param value - The value to be validated.
670
670
  * @returns An object with validation results.
671
671
  */
672
- callback?(value: string | number): { fail: boolean; errorMessage?: string };
672
+ callback?(value: string | number): boolean;
673
673
 
674
674
  /**
675
675
  * Specifies a numeric range for the value.
@@ -1371,14 +1371,17 @@ Templates are already a great power of form-engine, but we can go further allowi
1371
1371
  {
1372
1372
  "component": "input",
1373
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
1374
  "validations": {
1379
- "ON_FIELD_CHANGE": {
1375
+ "methods": {
1380
1376
  "required": true,
1381
1377
  "value": "varOps.concatenate(${fields.email.value||0},${fields.email2.value||0})"
1378
+ },
1379
+ "eventMessages": {
1380
+ "ON_FIELD_CHANGE": ["required", "value" ]
1381
+ },
1382
+ "messages": {
1383
+ "required": "Password is required",
1384
+ "value": "Error value must be varOps.concatenate(${fields.email.value||0},${fields.email2.value||0})"
1382
1385
  }
1383
1386
  },
1384
1387
  "props": {
@@ -1416,9 +1419,12 @@ Since we are already using [templates](#templates) to run our varOps and subscri
1416
1419
 
1417
1420
  ```json
1418
1421
  {
1419
- "errorMessages": {
1420
- "required": "Password is required",
1421
- "value": "Error value must be foo_bar"
1422
+ "validations": {
1423
+ ...,
1424
+ "messages": {
1425
+ "required": "Password is required",
1426
+ "value": "Error value must be foo_bar"
1427
+ }
1422
1428
  }
1423
1429
  }
1424
1430
  ```
@@ -1576,9 +1582,7 @@ Or Simply using the form reference in a button outside the form, for example:
1576
1582
  {
1577
1583
  const ref = useRef < TFormRefActions > null;
1578
1584
 
1579
- return (
1580
- <Form id="form" ref={ref} onClick={() => ref.current?.stepForward()} />
1581
- );
1585
+ return <Form id="form" ref={ref} onClick={() => ref.current?.stepForward()} />;
1582
1586
  }
1583
1587
 
1584
1588
  // --------------------- OR --------------------- //
package/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Subject, Subscription, combineLatest, startWith, groupBy, mergeMap, debounceTime, filter, map } from 'rxjs';
2
2
  import creditCardType from 'credit-card-type';
3
- import { isNumber as isNumber$1, isEqual, get, isNil, set } from 'lodash';
3
+ import { isNumber as isNumber$1, isFunction, isEqual, get, isNil, set } from 'lodash';
4
4
  import { getCurrencySymbol } from '@gaignoux/currency';
5
5
 
6
6
  var TMutationEnum;
@@ -44,6 +44,12 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
44
44
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
45
45
  };
46
46
 
47
+ const DEFAULT_API_DEBOUNCE_TIME = 1000;
48
+ const DEFAULT_STATE_REFRESH_TIME = 100;
49
+ const TEMPLATE_REGEX_DELIMITATOR = /\${(.*?)}/g;
50
+ const TEMPLATE_REGEX_OPERATOR_SPLITTER = /\s*(\|\||&&|!)\s*/g;
51
+ const TEMPLATE_REGEX_OPERATOR_MATCHER = /^\|\||&&|!$/;
52
+
47
53
  /**
48
54
  * Makes an HTTP request using XMLHttpRequest.
49
55
  *
@@ -96,15 +102,17 @@ function makeRequest(method, url, headers, body) {
96
102
  * ```
97
103
  */
98
104
  function extractFieldKeys(expression) {
99
- const regex = /\${(.*?)}/g;
105
+ const regex = TEMPLATE_REGEX_DELIMITATOR;
100
106
  const extractedValues = [];
101
107
  let match;
102
108
  while ((match = regex.exec(expression)) !== null) {
103
109
  extractedValues.push(match[1]);
104
110
  }
111
+ const operatorRegex = TEMPLATE_REGEX_OPERATOR_SPLITTER;
112
+ const splittedString = extractedValues.map(el => el.split(operatorRegex).filter(item => !operatorRegex.test(item))).flat().filter(el => el.split('.').length > 1);
105
113
  return {
106
- originFieldKeys: Array.from(new Set(extractedValues.map(el => el.split('.')[0]))),
107
- originPropertyKeys: Array.from(new Set(extractedValues.map(el => el.split('.')[1])))
114
+ originFieldKeys: Array.from(new Set(splittedString.map(el => el.split('.')[0]))),
115
+ originPropertyKeys: Array.from(new Set(splittedString.map(el => el.split('.')[1])))
108
116
  };
109
117
  }
110
118
  /**
@@ -2109,6 +2117,34 @@ const validDate = (value, validations) => {
2109
2117
  return !isValidDate;
2110
2118
  };
2111
2119
 
2120
+ /**
2121
+ * @internal
2122
+ * Runs a set of validation handlers against a given value.
2123
+ *
2124
+ * @param {unknown} value - The value to be validated.
2125
+ * @param {TValidationMethods} handlers - An object containing validation methods to be applied.
2126
+ * @param {TValidationHandler} validations - An object containing every validation methods to be executed.
2127
+ * @returns {boolean[]} - An array of boolean results for each validation method.
2128
+ *
2129
+ * @example
2130
+ * const handlers = {
2131
+ * max: { max: 10 },
2132
+ * required: true,
2133
+ * email: true
2134
+ * };
2135
+ * const results = run('test@example.com', handlers);
2136
+ * console.log(results); // [false, false, true] (value fails 'max', passes 'required', passes 'email')
2137
+ */
2138
+ function runner(value, handlers, validations) {
2139
+ const runner = [];
2140
+ Object.keys(handlers).forEach(rule => {
2141
+ runner.push(validations[rule](value, {
2142
+ [rule]: handlers[rule]
2143
+ }));
2144
+ });
2145
+ return runner;
2146
+ }
2147
+
2112
2148
  /**
2113
2149
  * @internal
2114
2150
  * An object mapping validation keys to their respective validation functions.
@@ -2119,7 +2155,7 @@ const validDate = (value, validations) => {
2119
2155
  * const isValid = validations.max(5, { max: 10 });
2120
2156
  * console.log(isValid); // false (5 is not greater than 10)
2121
2157
  */
2122
- const validations$1 = {
2158
+ const validations$2 = {
2123
2159
  max,
2124
2160
  min,
2125
2161
  length,
@@ -2143,44 +2179,17 @@ const validations$1 = {
2143
2179
  notEmpty,
2144
2180
  bool,
2145
2181
  exists,
2146
- greaterThan: () => true,
2147
2182
  isNumber,
2148
2183
  conditions,
2149
2184
  validDate,
2150
2185
  date,
2151
2186
  betweenDates
2152
2187
  };
2153
- /**
2154
- * @internal
2155
- * Runs a set of validation handlers against a given value.
2156
- *
2157
- * @param {unknown} value - The value to be validated.
2158
- * @param {TValidationMethods} handlers - An object containing validation methods to be applied.
2159
- * @returns {boolean[]} - An array of boolean results for each validation method.
2160
- *
2161
- * @example
2162
- * const handlers = {
2163
- * max: { max: 10 },
2164
- * required: true,
2165
- * email: true
2166
- * };
2167
- * const results = run('test@example.com', handlers);
2168
- * console.log(results); // [false, false, true] (value fails 'max', passes 'required', passes 'email')
2169
- */
2170
- const run = (value, handlers) => {
2171
- const runner = [];
2172
- Object.keys(handlers).forEach(rule => {
2173
- runner.push(validations$1[rule](value, {
2174
- [rule]: handlers[rule]
2175
- }));
2176
- });
2177
- return runner;
2178
- };
2179
2188
  /**
2180
2189
  * Validates that a value meets multiple validation rules.
2181
2190
  *
2182
2191
  * @param {number | string | boolean} value - The value to be validated.
2183
- * @param {TValidationMethods} validations - The validation methods object containing the multipleValidations rule set.
2192
+ * @param {TValidationMethods} methods - The validation methods object containing the multipleValidations rule set.
2184
2193
  * @returns {boolean} - Returns `true` if the value meets the specified multiple validation rules, otherwise `false`.
2185
2194
  *
2186
2195
  * @example
@@ -2205,18 +2214,18 @@ const run = (value, handlers) => {
2205
2214
  * console.log(result2); // false
2206
2215
  * ```
2207
2216
  */
2208
- const multipleValidations = (value, validations) => {
2209
- if (!validations.multipleValidations) return false;
2210
- const runner = run(value, validations.multipleValidations.validations);
2217
+ const multipleValidations = (value, methods) => {
2218
+ if (!methods.multipleValidations) return false;
2219
+ const runner$1 = runner(value, methods.multipleValidations.validations, validations$2);
2211
2220
  const rulesMapper = {
2212
- AND: () => runner.every(validation => validation),
2213
- OR: () => runner.some(validation => validation),
2214
- NOT: () => !runner.every(validation => validation)
2221
+ AND: () => runner$1.every(validation => validation),
2222
+ OR: () => runner$1.some(validation => validation),
2223
+ NOT: () => !runner$1.every(validation => validation)
2215
2224
  };
2216
- return rulesMapper[validations.multipleValidations.rule]();
2225
+ return rulesMapper[methods.multipleValidations.rule]();
2217
2226
  };
2218
2227
 
2219
- const validations = {
2228
+ const validations$1 = {
2220
2229
  max,
2221
2230
  min,
2222
2231
  length,
@@ -2240,7 +2249,6 @@ const validations = {
2240
2249
  notEmpty,
2241
2250
  bool,
2242
2251
  exists,
2243
- greaterThan: () => true,
2244
2252
  isNumber,
2245
2253
  conditions,
2246
2254
  multipleValidations,
@@ -2249,9 +2257,6 @@ const validations = {
2249
2257
  validDate
2250
2258
  };
2251
2259
 
2252
- const DEFAULT_API_DEBOUNCE_TIME = 1000;
2253
- const DEFAULT_STATE_REFRESH_TIME = 100;
2254
-
2255
2260
  /**
2256
2261
  * Custom RXJS Subject to gracefully handle errors on unsubscribed Subjects
2257
2262
  * that were unmounted due to adapter external handling such as visibility
@@ -2268,6 +2273,100 @@ class SafeSubject extends Subject {
2268
2273
  }
2269
2274
  }
2270
2275
 
2276
+ /**
2277
+ * @internal
2278
+ * An object mapping validation keys to their respective validation functions.
2279
+ *
2280
+ * @type {Record<keyof TAvailableValidations, (value: unknown, validations: TAvailableValidations) => boolean>}
2281
+ *
2282
+ * @example
2283
+ * const isValid = validations.max(5, { max: 10 });
2284
+ * console.log(isValid); // false (5 is not greater than 10)
2285
+ */
2286
+ const validations = {
2287
+ max,
2288
+ min,
2289
+ length,
2290
+ regex,
2291
+ url,
2292
+ email,
2293
+ onlyLetters,
2294
+ notAllowSpaces,
2295
+ callback,
2296
+ hasNoExtraSpaces,
2297
+ between,
2298
+ sequential,
2299
+ includes,
2300
+ repeated,
2301
+ document,
2302
+ isCreditCard,
2303
+ isCreditCodeMatch,
2304
+ isCreditCardAndLength,
2305
+ required,
2306
+ value,
2307
+ notEmpty,
2308
+ bool,
2309
+ exists,
2310
+ isNumber,
2311
+ conditions,
2312
+ validDate,
2313
+ date,
2314
+ betweenDates,
2315
+ multipleValidations
2316
+ };
2317
+ /**
2318
+ * Validates a given value based on specified validation methods inside a custom named validation.
2319
+ *
2320
+ * @param {unknown} value - The value to be validated.
2321
+ * @param {TValidationMethods} methods - The validation methods to be applied.
2322
+ * @returns {boolean} - Returns true if any of the validation methods pass, otherwise false.
2323
+ *
2324
+ * @example
2325
+ * const value = 'example@example.com';
2326
+ * const methods = {
2327
+ * required: true,
2328
+ * email: true
2329
+ * };
2330
+ *
2331
+ * const isValid = validateValue(value, methods);
2332
+ * console.log(isValid); // Output: true
2333
+ */
2334
+ var namedRule = ((value, methods) => {
2335
+ if (!methods) return false;
2336
+ return runner(value, methods, validations).some(validation => validation);
2337
+ });
2338
+
2339
+ /**
2340
+ * @internal
2341
+ * Handles the validation of a given value based on specified validation methods and rules.
2342
+ *
2343
+ * @param {string | number | boolean | unknown} value - The value to be validated.
2344
+ * @param {TSchemaValidation} validations - The schema validations to be applied.
2345
+ * @param {TValidationHandler} methods - The validation handler methods.
2346
+ * @param {keyof TValidationMethods} key - The specific key of the validation method to be used.
2347
+ * @returns {boolean} - Returns true if the value passes the validation, otherwise false.
2348
+ *
2349
+ * @example
2350
+ * const value = 'example@example.com';
2351
+ * const validations = {
2352
+ * required: true,
2353
+ * customName: { email: true }
2354
+ * };
2355
+ * const methods = {
2356
+ * email: (value) => /\S+@\S+\.\S+/.test(value)
2357
+ * };
2358
+ * const key = 'required';
2359
+ *
2360
+ * const isValid = handleValidation(value, validations, methods, key);
2361
+ * console.log(isValid); // Output: true
2362
+ */
2363
+ function handleValidation(value, validations, methods, key) {
2364
+ if (isFunction(methods[key])) {
2365
+ return methods[key](value, validations);
2366
+ }
2367
+ return namedRule(value, validations[key]);
2368
+ }
2369
+
2271
2370
  /**
2272
2371
  * Represents a form field with observables for managing form state, validations, and API requests.
2273
2372
  */
@@ -2658,7 +2757,7 @@ class FormField {
2658
2757
  const errors = {};
2659
2758
  const schemaValidations = (_a = this.validations) === null || _a === void 0 ? void 0 : _a.methods;
2660
2759
  schemaValidations && Object.keys(schemaValidations).forEach(validationKey => {
2661
- const error = validations[validationKey](this.value, schemaValidations);
2760
+ const error = handleValidation(this.value, schemaValidations, validations$1, validationKey);
2662
2761
  // setting valid flag
2663
2762
  valid = !error && valid;
2664
2763
  // setting error messages
@@ -2718,7 +2817,7 @@ class FormField {
2718
2817
  let valid = true;
2719
2818
  const preConditions = config.preConditions;
2720
2819
  preConditions && Object.keys(preConditions).forEach(validationKey => {
2721
- const error = validations[validationKey](this.value, preConditions);
2820
+ const error = handleValidation(this.value, preConditions, validations$1, validationKey);
2722
2821
  valid = valid && !error;
2723
2822
  });
2724
2823
  if (config.blockRequestWhenInvalid) {
@@ -2861,7 +2960,6 @@ class FormCore {
2861
2960
  * @param {string} [entry.action] - The action attribute of the form.
2862
2961
  * @param {string} [entry.method] - The method attribute of the form.
2863
2962
  * @param {IFormSchema.iVars} [entry.iVars] - The internal variables of the form.
2864
- * @param {(data: TFormValues) => void} [entry.onSubmit] - A callback function to handle form submission.
2865
2963
  * @param {((payload: {field: string;data: TFormValues;}) => void) | undefined} [entry.onData] - A callback function to handle data emission.
2866
2964
  */
2867
2965
  constructor(entry) {
@@ -2873,7 +2971,6 @@ class FormCore {
2873
2971
  this.action = entry.action || ((_b = entry.schema) === null || _b === void 0 ? void 0 : _b.action);
2874
2972
  this.method = entry.method || ((_c = entry.schema) === null || _c === void 0 ? void 0 : _c.method);
2875
2973
  this._iVars = entry.iVars || ((_d = entry.schema) === null || _d === void 0 ? void 0 : _d.iVars) || {};
2876
- this.onSubmit = entry.onSubmit;
2877
2974
  this.config = {
2878
2975
  defaultAPIdebounceTimeMS: Number((_e = entry.config) === null || _e === void 0 ? void 0 : _e.defaultAPIdebounceTimeMS) ? Number((_f = entry.config) === null || _f === void 0 ? void 0 : _f.defaultAPIdebounceTimeMS) : DEFAULT_API_DEBOUNCE_TIME,
2879
2976
  defaultStateRefreshTimeMS: Number((_g = entry.config) === null || _g === void 0 ? void 0 : _g.defaultStateRefreshTimeMS) ? Number((_h = entry.config) === null || _h === void 0 ? void 0 : _h.defaultStateRefreshTimeMS) : DEFAULT_STATE_REFRESH_TIME
@@ -2886,7 +2983,6 @@ class FormCore {
2886
2983
  this.submitSubject$ = new Subject();
2887
2984
  this.fieldEventSubject$ = new Subject();
2888
2985
  this.dataSubject$ = new Subject();
2889
- this.dataCallbackSubscription$ = new Subscription();
2890
2986
  this.subscribedTemplates = [];
2891
2987
  this.schema && this.serializeStructure(this.schema.components);
2892
2988
  this.schema && this.subscribeTemplates();
@@ -2895,7 +2991,6 @@ class FormCore {
2895
2991
  key: IVARPROPNAME,
2896
2992
  event: 'ON_IVARS'
2897
2993
  });
2898
- entry.onData && this.subscribeData(entry.onData);
2899
2994
  /*
2900
2995
  mount events needs to occur on form level, only when all the fields are instantiated
2901
2996
  is it possible to apply all the side effects that occur globally, same effect occur
@@ -2970,20 +3065,6 @@ class FormCore {
2970
3065
  traverseObject(template, key).forEach(element => this.subscribedTemplates.push(element));
2971
3066
  });
2972
3067
  }
2973
- /**
2974
- *
2975
- * @param {(payload: { field: string; data: TFormValues }) => void} callback callback function to call on data
2976
- */
2977
- subscribeData(callback) {
2978
- this.dataCallbackSubscription$ = this.dataSubject$.pipe(debounceTime(this.config.defaultStateRefreshTimeMS), map(({
2979
- key
2980
- }) => ({
2981
- field: key,
2982
- data: this.getFormValues()
2983
- }))).subscribe({
2984
- next: callback
2985
- });
2986
- }
2987
3068
  /**
2988
3069
  * Gets the value of a property from a field.
2989
3070
  *
@@ -3070,17 +3151,17 @@ class FormCore {
3070
3151
  * @returns {string[]} An array of extracted parameters.
3071
3152
  */
3072
3153
  extractParams(expression) {
3073
- const regex = /\${(.*?)}/g;
3154
+ const regex = TEMPLATE_REGEX_DELIMITATOR;
3074
3155
  const extractedValues = [];
3075
3156
  let match;
3076
3157
  while (!isNil(match = regex.exec(expression))) {
3077
3158
  extractedValues.push(match[1]);
3078
3159
  }
3079
- const operatorRegex = /\s*(\|\||&&|!)\s*/g;
3160
+ const operatorRegex = TEMPLATE_REGEX_OPERATOR_SPLITTER;
3080
3161
  const splittedString = extractedValues.map(el => el.split(operatorRegex));
3081
3162
  const result = splittedString.map(splittedStringVal => {
3082
3163
  return splittedStringVal.filter(Boolean).reduce((acc, curr) => {
3083
- if (curr.match(/^\|\||&&|!$/)) {
3164
+ if (curr.match(TEMPLATE_REGEX_OPERATOR_MATCHER)) {
3084
3165
  return `${acc}${curr}`;
3085
3166
  }
3086
3167
  let value;
@@ -3142,7 +3223,7 @@ class FormCore {
3142
3223
  * @returns {string} The expression string with the replacements made.
3143
3224
  */
3144
3225
  replaceExpression(expression, values) {
3145
- const regex = /\${(.*?)}/g;
3226
+ const regex = TEMPLATE_REGEX_DELIMITATOR;
3146
3227
  return expression.replace(regex, () => String(values.shift()) || '');
3147
3228
  }
3148
3229
  /**
@@ -3216,7 +3297,7 @@ class FormCore {
3216
3297
  structVisibility.forEach(structElement => {
3217
3298
  if (!structElement.events.includes(event)) return;
3218
3299
  Object.keys(structElement.validations).forEach(validationKey => {
3219
- const error = validations[validationKey](field.value, structElement.validations);
3300
+ const error = handleValidation(field.value, structElement.validations, validations$1, validationKey);
3220
3301
  if (Array.isArray(structElement.fields)) {
3221
3302
  structElement.fields.forEach(fieldKey => {
3222
3303
  if (!this.fields.has(fieldKey)) console.warn(`failed to update visibility onto field ${fieldKey}`);else this.fields.get(fieldKey).visibility = !error;
@@ -3244,7 +3325,7 @@ class FormCore {
3244
3325
  structResetValue.forEach(structElement => {
3245
3326
  if (!structElement.events.includes(event)) return;
3246
3327
  Object.keys(structElement.validations).forEach(validationKey => {
3247
- const error = validations[validationKey](field.value, structElement.validations);
3328
+ const error = handleValidation(field.value, structElement.validations, validations$1, validationKey);
3248
3329
  if (!error) {
3249
3330
  if (Array.isArray(structElement.fields)) {
3250
3331
  structElement.fields.forEach((fieldKey, index) => {
@@ -3443,6 +3524,27 @@ class FormCore {
3443
3524
  });
3444
3525
  return sub;
3445
3526
  }
3527
+ /**
3528
+ *
3529
+ * @param {(payload: { field: string; data: TFormValues }) => void} callback callback function to call on data
3530
+ */
3531
+ subscribeData(callback) {
3532
+ const sub = this.dataSubject$.pipe(groupBy(payload => payload.event), mergeMap(group$ => group$.pipe(debounceTime(this.config.defaultStateRefreshTimeMS))), map(({
3533
+ key
3534
+ }) => ({
3535
+ field: key,
3536
+ data: this.getFormValues()
3537
+ }))).subscribe({
3538
+ next: callback
3539
+ });
3540
+ return sub;
3541
+ }
3542
+ subscribeOnSubmit(callback) {
3543
+ const sub = this.submitSubject$.pipe(map(() => this.getFormValues())).subscribe({
3544
+ next: callback
3545
+ });
3546
+ return sub;
3547
+ }
3446
3548
  /**
3447
3549
  * Submits the form by triggering form field events and invoking the onSubmit callback.
3448
3550
  */
@@ -3455,7 +3557,6 @@ class FormCore {
3455
3557
  if (!this.isValid) return;
3456
3558
  const values = this.getFormValues();
3457
3559
  this.submitSubject$.next(values);
3458
- this.onSubmit && this.onSubmit(values);
3459
3560
  }
3460
3561
  destroy() {
3461
3562
  this.submitSubject$.unsubscribe();
@@ -3606,22 +3707,49 @@ class FormGroup {
3606
3707
  * @param {string[]} indexes form indexes to be submitted
3607
3708
  * @returns
3608
3709
  */
3609
- submitMultipleFormsByIndex(indexes) {
3710
+ submitMultipleFormsByIndex(indexes, callback) {
3610
3711
  let isValid = true;
3611
3712
  let values = {};
3612
3713
  let erroredFields = [];
3613
3714
  indexes.forEach(index => {
3614
- var _a;
3615
- const res = (_a = this.forms.get(index)) === null || _a === void 0 ? void 0 : _a.getFormValues();
3715
+ var _a, _b;
3716
+ (_a = this.forms.get(index)) === null || _a === void 0 ? void 0 : _a.submit();
3717
+ const res = (_b = this.forms.get(index)) === null || _b === void 0 ? void 0 : _b.getFormValues();
3616
3718
  isValid = isValid && ((res === null || res === void 0 ? void 0 : res.isValid) || false);
3617
3719
  values = Object.assign(Object.assign({}, values), (res === null || res === void 0 ? void 0 : res.values) || {});
3618
3720
  erroredFields = [...erroredFields, ...((res === null || res === void 0 ? void 0 : res.erroredFields) || [])];
3619
3721
  });
3620
- return {
3722
+ isValid && callback && callback({
3621
3723
  erroredFields,
3622
3724
  isValid,
3623
3725
  values
3624
- };
3726
+ });
3727
+ }
3728
+ onDataSubscription({
3729
+ ids,
3730
+ callback
3731
+ }) {
3732
+ const subs = ids.reduce((acc, formId) => {
3733
+ var _a;
3734
+ // @TODO add config on debounceTime on this events
3735
+ const sub = (_a = this.forms.get(formId)) === null || _a === void 0 ? void 0 : _a.dataSubject$.pipe(groupBy(payload => `${formId}.${payload.event}`), mergeMap(group$ => group$.pipe(debounceTime(100))), map(({
3736
+ key
3737
+ }) => {
3738
+ var _a;
3739
+ return {
3740
+ formField: key,
3741
+ values: (_a = this.forms.get(formId)) === null || _a === void 0 ? void 0 : _a.getFormValues()
3742
+ };
3743
+ }));
3744
+ if (sub) {
3745
+ acc[formId] = sub;
3746
+ } else {
3747
+ console.warn(`failed to register form id ${formId}`);
3748
+ }
3749
+ return acc;
3750
+ }, {});
3751
+ const sub = combineLatest(subs).subscribe(callback);
3752
+ return sub;
3625
3753
  }
3626
3754
  }
3627
3755
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolttech/form-engine-core",
3
- "version": "0.0.1-beta.16",
3
+ "version": "0.0.1-beta.18",
4
4
  "module": "./index.esm.js",
5
5
  "type": "module",
6
6
  "main": "./index.esm.js",
@@ -1,3 +1,6 @@
1
1
  declare const DEFAULT_API_DEBOUNCE_TIME = 1000;
2
2
  declare const DEFAULT_STATE_REFRESH_TIME = 100;
3
- export { DEFAULT_API_DEBOUNCE_TIME, DEFAULT_STATE_REFRESH_TIME };
3
+ declare const TEMPLATE_REGEX_DELIMITATOR: RegExp;
4
+ declare const TEMPLATE_REGEX_OPERATOR_SPLITTER: RegExp;
5
+ declare const TEMPLATE_REGEX_OPERATOR_MATCHER: RegExp;
6
+ export { DEFAULT_API_DEBOUNCE_TIME, DEFAULT_STATE_REFRESH_TIME, TEMPLATE_REGEX_DELIMITATOR, TEMPLATE_REGEX_OPERATOR_SPLITTER, TEMPLATE_REGEX_OPERATOR_MATCHER };
@@ -0,0 +1,27 @@
1
+ import { TSchemaValidation, TValidationMethods } from '../../types/schema';
2
+ import { TValidationHandler } from '../../validations/handler';
3
+ /**
4
+ * @internal
5
+ * Handles the validation of a given value based on specified validation methods and rules.
6
+ *
7
+ * @param {string | number | boolean | unknown} value - The value to be validated.
8
+ * @param {TSchemaValidation} validations - The schema validations to be applied.
9
+ * @param {TValidationHandler} methods - The validation handler methods.
10
+ * @param {keyof TValidationMethods} key - The specific key of the validation method to be used.
11
+ * @returns {boolean} - Returns true if the value passes the validation, otherwise false.
12
+ *
13
+ * @example
14
+ * const value = 'example@example.com';
15
+ * const validations = {
16
+ * required: true,
17
+ * customName: { email: true }
18
+ * };
19
+ * const methods = {
20
+ * email: (value) => /\S+@\S+\.\S+/.test(value)
21
+ * };
22
+ * const key = 'required';
23
+ *
24
+ * const isValid = handleValidation(value, validations, methods, key);
25
+ * console.log(isValid); // Output: true
26
+ */
27
+ export default function handleValidation(value: string | number | boolean | unknown, validations: TSchemaValidation, methods: TValidationHandler, key: keyof TValidationMethods): boolean;
@@ -0,0 +1,21 @@
1
+ import { TValidationMethods } from '../../types/schema';
2
+ import { TValidationHandler } from '../../validations/handler';
3
+ /**
4
+ * @internal
5
+ * Runs a set of validation handlers against a given value.
6
+ *
7
+ * @param {unknown} value - The value to be validated.
8
+ * @param {TValidationMethods} handlers - An object containing validation methods to be applied.
9
+ * @param {TValidationHandler} validations - An object containing every validation methods to be executed.
10
+ * @returns {boolean[]} - An array of boolean results for each validation method.
11
+ *
12
+ * @example
13
+ * const handlers = {
14
+ * max: { max: 10 },
15
+ * required: true,
16
+ * email: true
17
+ * };
18
+ * const results = run('test@example.com', handlers);
19
+ * console.log(results); // [false, false, true] (value fails 'max', passes 'required', passes 'email')
20
+ */
21
+ export default function runner(value: unknown, handlers: TValidationMethods, validations: TValidationHandler): boolean[];
@@ -24,13 +24,11 @@ declare class FormCore {
24
24
  key: string;
25
25
  event: TEvents;
26
26
  }>;
27
- dataCallbackSubscription$: Subscription;
28
27
  subscribedTemplates: TSubscribedTemplates[];
29
28
  action?: string;
30
29
  method?: string;
31
30
  config: Required<TSchemaFormConfig>;
32
31
  mappers: Map<string, TMapper<unknown>>;
33
- onSubmit?: (data: TFormValues<Record<string, unknown>>) => void;
34
32
  /**
35
33
  * Creates an instance of FormCore.
36
34
  *
@@ -40,7 +38,6 @@ declare class FormCore {
40
38
  * @param {string} [entry.action] - The action attribute of the form.
41
39
  * @param {string} [entry.method] - The method attribute of the form.
42
40
  * @param {IFormSchema.iVars} [entry.iVars] - The internal variables of the form.
43
- * @param {(data: TFormValues) => void} [entry.onSubmit] - A callback function to handle form submission.
44
41
  * @param {((payload: {field: string;data: TFormValues;}) => void) | undefined} [entry.onData] - A callback function to handle data emission.
45
42
  */
46
43
  constructor(entry: TFormEntry & Omit<IFormSchema, 'components'>);
@@ -66,14 +63,6 @@ declare class FormCore {
66
63
  * Subscribes to templates for dynamic updates.
67
64
  */
68
65
  subscribeTemplates(): void;
69
- /**
70
- *
71
- * @param {(payload: { field: string; data: TFormValues }) => void} callback callback function to call on data
72
- */
73
- subscribeData(callback: (payload: {
74
- field: string;
75
- data: TFormValues<Record<string, unknown>>;
76
- }) => void): void;
77
66
  /**
78
67
  * Gets the value of a property from a field.
79
68
  *
@@ -220,6 +209,15 @@ declare class FormCore {
220
209
  subscribeFieldEvent({ callback, }: {
221
210
  callback: (payload: TFieldEvent) => void;
222
211
  }): Subscription;
212
+ /**
213
+ *
214
+ * @param {(payload: { field: string; data: TFormValues }) => void} callback callback function to call on data
215
+ */
216
+ subscribeData(callback: (payload: {
217
+ field: string;
218
+ data: TFormValues<Record<string, unknown>>;
219
+ }) => void): Subscription;
220
+ subscribeOnSubmit(callback: (payload: TFormValues<Record<string, unknown>>) => void): Subscription;
223
221
  /**
224
222
  * Submits the form by triggering form field events and invoking the onSubmit callback.
225
223
  */
@@ -79,7 +79,15 @@ declare class FormGroup {
79
79
  * @param {string[]} indexes form indexes to be submitted
80
80
  * @returns
81
81
  */
82
- submitMultipleFormsByIndex<T>(indexes: string[]): TFormValues<T>;
82
+ submitMultipleFormsByIndex<T>(indexes: string[], callback?: (payload: TFormValues<T>) => void): void;
83
+ onDataSubscription({ ids, callback, }: {
84
+ ids: string[];
85
+ callback: (payload: Record<string, {
86
+ formId: string;
87
+ formField: string;
88
+ values?: TFormValues<Record<string, unknown>>;
89
+ }>) => void;
90
+ }): import("rxjs").Subscription;
83
91
  }
84
92
  type TFormGroup = FormGroup;
85
93
  export { TFormGroup, FormGroup };
@@ -41,11 +41,6 @@ type TFormValues<T> = {
41
41
  */
42
42
  type TFormEntry = Omit<IFormSchema, 'components'> & {
43
43
  schema?: IFormSchema;
44
- onSubmit?: <T>(data: TFormValues<T>) => void;
45
- onData?: <T>(payload: {
46
- field: string;
47
- data: TFormValues<T>;
48
- }) => void;
49
44
  mappers?: TMapper<unknown>[];
50
45
  };
51
46
  export { TFormValues, TFormEntry };
@@ -313,7 +313,6 @@ type TDateValidation = {
313
313
  * @property {number} [min] - Minimum value or length.
314
314
  * @property {TLengthValidation} [length] - Length validation rule.
315
315
  * @property {boolean} [required] - Indicates if the field is required.
316
- * @property {number} [greaterThan] - Value must be greater than this number.
317
316
  * @property {unknown} [value] - Specific value to match.
318
317
  * @property {string} [regex] - Regular expression for validation.
319
318
  * @property {boolean} [email] - Indicates if the value should be a valid email.
@@ -397,7 +396,6 @@ type TValidationMethods = {
397
396
  min?: number;
398
397
  length?: TLengthValidation;
399
398
  required?: boolean;
400
- greaterThan?: number;
401
399
  value?: unknown;
402
400
  regex?: string;
403
401
  email?: boolean;
@@ -424,6 +422,47 @@ type TValidationMethods = {
424
422
  date?: TDateValidation;
425
423
  validDate?: TDateFormatsValidation;
426
424
  };
425
+ /**
426
+ * @type {Object.<string, TValidationMethods>} TGenericValidationRule
427
+ * Represents a generic validation rule where each key is associated with a set of validation methods.
428
+ *
429
+ * @example
430
+ * const genericValidationRule = {
431
+ * email: {
432
+ * required: true,
433
+ * email: true,
434
+ * },
435
+ * password: {
436
+ * required: true,
437
+ * minLength: 8,
438
+ * },
439
+ * };
440
+ */
441
+ type TGenericValidationRule = {
442
+ [key: string]: TValidationMethods;
443
+ };
444
+ /**
445
+ * @type {TValidationMethods | TGenericValidationRule} TSchemaValidation
446
+ * Represents the schema validation which can be either a set of validation methods or a generic validation rule.
447
+ *
448
+ * @example
449
+ * const schemaValidation = {
450
+ * required: true,
451
+ * maxLength: 10,
452
+ * };
453
+ *
454
+ * const genericSchemaValidation = {
455
+ * email: {
456
+ * required: true,
457
+ * email: true,
458
+ * },
459
+ * password: {
460
+ * required: true,
461
+ * minLength: 8,
462
+ * },
463
+ * };
464
+ */
465
+ type TSchemaValidation = TValidationMethods | TGenericValidationRule;
427
466
  /**
428
467
  * Formatter types
429
468
  * @type TSplitterFormatterValue
@@ -579,7 +618,7 @@ type TMasks = {
579
618
  * @type TVisibility
580
619
  * Represents the visibility conditions for form fields based on validations.
581
620
  *
582
- * @property {TValidationMethods} validations - The validation methods to determine visibility.
621
+ * @property {TSchemaValidation} validations - The validation methods to determine visibility.
583
622
  * @property {string[] | string} fields - The fields to be shown or hidden based on validations.
584
623
  *
585
624
  * @example
@@ -591,7 +630,7 @@ type TMasks = {
591
630
  * ```
592
631
  */
593
632
  type TVisibility = {
594
- validations: TValidationMethods;
633
+ validations: TSchemaValidation;
595
634
  fields: string[] | string;
596
635
  events: Partial<TEvents>[];
597
636
  };
@@ -622,7 +661,7 @@ type TResetValueMethods = TVisibility & {
622
661
  * @property {OutgoingHttpHeaders} [headers] - The headers for the request.
623
662
  * @property {string} [resultPath] - The path to extract the result from the response.
624
663
  * @property {unknown} [fallbackValue] - The fallback value if the request fails.
625
- * @property {TValidationMethods} preConditions - validation conditions to execute the API call
664
+ * @property {TSchemaValidation} preConditions - validation conditions to execute the API call
626
665
  * @property {boolean} blockRequestWhenInvalid - blocks request when field validation fails
627
666
  *
628
667
  * @example
@@ -647,7 +686,7 @@ type TApiConfig = {
647
686
  headers?: OutgoingHttpHeaders;
648
687
  resultPath?: string;
649
688
  fallbackValue?: unknown;
650
- preConditions?: TValidationMethods;
689
+ preConditions?: TSchemaValidation;
651
690
  blockRequestWhenInvalid?: boolean;
652
691
  };
653
692
  /**
@@ -659,7 +698,7 @@ type TProps = Record<string, unknown>;
659
698
  * @type TValidations
660
699
  * Represents the validation configuration for form fields, including methods, event-specific messages, and error messages.
661
700
  *
662
- * @property {TValidationMethods} methods - The validation methods to be applied.
701
+ * @property {TSchemaValidation} methods - The validation methods to be applied.
663
702
  * @property {Partial<Record<TEvents, string[]>>} eventMessages - The messages to be displayed for specific validation events.
664
703
  * @property {TErrorMessages} messages - The general error messages for validation methods.
665
704
  *
@@ -683,7 +722,7 @@ type TProps = Record<string, unknown>;
683
722
  * };
684
723
  */
685
724
  type TValidations = {
686
- methods: TValidationMethods;
725
+ methods: TSchemaValidation;
687
726
  eventMessages?: Partial<Record<TEvents, string[]>>;
688
727
  messages?: TErrorMessages;
689
728
  };
@@ -700,7 +739,7 @@ type TValidations = {
700
739
  * };
701
740
  * ```
702
741
  */
703
- type TErrorMessages = Partial<Record<keyof TValidationMethods & 'default', string>>;
742
+ type TErrorMessages = Partial<Record<keyof TSchemaValidation & 'default', string>>;
704
743
  /**
705
744
  * Represents an event configuration with a specific type.
706
745
  *
@@ -746,4 +785,4 @@ type TSchemaFormConfig = {
746
785
  defaultAPIdebounceTimeMS?: number;
747
786
  defaultStateRefreshTimeMS?: number;
748
787
  };
749
- export { TApiConfig, TErrorMessages, TValidations, TMasks, TProps, TResetValueMethods, TFormatters, TValidationMethods, TEvent, TVisibility, TApiEvent, TApiResponse, TSchemaFormConfig, TLengthValidation, TCreditCardMatch, TDocumentValidation, TCallbackValidation, TBetweenValidation, TMaskGeneric, TSplitterFormatterValue, TCurrencyMask, TDateOperatorsValidation, TConditionsValidationSet, TConditionsValidation, TMultipleValidation, TAvailableValidations, TDateValidation, TBetweenDatesValidation, TDateFormatsValidation, TDateInterval, };
788
+ export { TApiConfig, TErrorMessages, TValidations, TMasks, TProps, TResetValueMethods, TFormatters, TValidationMethods, TGenericValidationRule, TSchemaValidation, TEvent, TVisibility, TApiEvent, TApiResponse, TSchemaFormConfig, TLengthValidation, TCreditCardMatch, TDocumentValidation, TCallbackValidation, TBetweenValidation, TMaskGeneric, TSplitterFormatterValue, TCurrencyMask, TDateOperatorsValidation, TConditionsValidationSet, TConditionsValidation, TMultipleValidation, TAvailableValidations, TDateValidation, TBetweenDatesValidation, TDateFormatsValidation, TDateInterval, };
@@ -1,2 +1,3 @@
1
1
  import { TValidationMethods } from '../types/schema';
2
- export declare const validations: Record<keyof TValidationMethods, (value: unknown, validations: TValidationMethods) => boolean>;
2
+ export type TValidationHandler = Record<string, (value: unknown, validations: TValidationMethods) => boolean>;
3
+ export declare const validations: TValidationHandler;
@@ -3,7 +3,7 @@ import { TValidationMethods } from '../types/schema';
3
3
  * Validates that a value meets multiple validation rules.
4
4
  *
5
5
  * @param {number | string | boolean} value - The value to be validated.
6
- * @param {TValidationMethods} validations - The validation methods object containing the multipleValidations rule set.
6
+ * @param {TValidationMethods} methods - The validation methods object containing the multipleValidations rule set.
7
7
  * @returns {boolean} - Returns `true` if the value meets the specified multiple validation rules, otherwise `false`.
8
8
  *
9
9
  * @example
@@ -28,4 +28,4 @@ import { TValidationMethods } from '../types/schema';
28
28
  * console.log(result2); // false
29
29
  * ```
30
30
  */
31
- export declare const multipleValidations: (value: number | string | boolean, validations: TValidationMethods) => boolean;
31
+ export declare const multipleValidations: (value: number | string | boolean, methods: TValidationMethods) => boolean;
@@ -0,0 +1,20 @@
1
+ import { TValidationMethods } from '../types/schema';
2
+ /**
3
+ * Validates a given value based on specified validation methods inside a custom named validation.
4
+ *
5
+ * @param {unknown} value - The value to be validated.
6
+ * @param {TValidationMethods} methods - The validation methods to be applied.
7
+ * @returns {boolean} - Returns true if any of the validation methods pass, otherwise false.
8
+ *
9
+ * @example
10
+ * const value = 'example@example.com';
11
+ * const methods = {
12
+ * required: true,
13
+ * email: true
14
+ * };
15
+ *
16
+ * const isValid = validateValue(value, methods);
17
+ * console.log(isValid); // Output: true
18
+ */
19
+ declare const _default: (value: unknown, methods: TValidationMethods) => boolean;
20
+ export default _default;